Can someone explain how to graph this sum in MATLAB using contourf?

雨燕双飞 提交于 2019-12-05 12:22:31

Vectorize the code. For example you can write f(x,y,n) with:

 [x y n] = meshgrid(-1:0.1:1,-1:0.1:1,1:10);
 f=exp(x.^2-y.^2).*n ;

f is a 3D matrix now just sum over the right dimension...

 g=sum(f,3);

in order to use contourf, we'll take only the 2D part of x,y:

 [x1 y1] = meshgrid(-1:0.1:1,-1:0.1:1);    
 contourf(x1,y1,g)

The reason your code takes so long to calculate the phi matrix is that you didn't pre-allocate the array. The error about size happens because phi is not 100x100. But instead of fixing those things, there's an even better way...

MATLAB is a MATrix LABoratory so this type of equation is pretty easy to compute using matrix operations. Hints:

  1. Instead of looping over the values, rows, or columns of x and y, construct matrices to represent all the possible input combinations. Check out meshgrid for this.

  2. You're still going to need a loop to sum over n = 1:N. But for each value of n, you can evaluate your equation for all x's and y's at once (using the matrices from hint 1). The key to making this work is using element-by-element operators, such as .* and ./.

Using matrix operations like this is The Matlab Way. Learn it and love it. (And get frustrated when using most other languages that don't have them.)

Good luck with your homework!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!