Nested for loop for contour plotting of Laplace equation
1 次查看(过去 30 天)
显示 更早的评论
![Capture.JPG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/231490/Capture.jpeg)
I am trying to plot the "contour" of this solution.
The code I have written using "nested for loop" :
- One for loop for varying x,
- Second inner for loop for varying y,
- And the final for loop for varying k.
I need to sum over k for fixed values of (x,y), that's why I have initialized two variables : sum and sumprev.
clc
clear all;
close all;
v0=100;
a=10;
b=5;
k=1:70;
n=(2*k)-1;
x=1:10/100:10;
y=1:5/100:5;
[X,Y,N]=meshgrid(x,y,k);
sumprev=0;
sum=0;
for i=1:length(X)
for j=1:length(Y)
for m=1:length(N)
sum(i,j,m)=sumprev+(4.*v0./pi).*(sin(m.*pi.*i./a).*(sinh(m.*pi.*j./a)./(m.*sinh(m.*pi.*b./a))));
sumprev=sum(i,j,m);
end
end
end
contour(X,Y,sum);
With meshgrid, I tried to create appropriate sizes of matrices. But after running the code, I get this error on my final line of the code:
Input arguments must have at most 2 dimensions.
Error in C5 (line 22)
contour(X,Y,sum);
Also, I checked my workspace and found that my variable sumprev is containing NaN value which seemed odd to me.
How to resolve this problem? Kindly help out if you can.
Thanks!
0 个评论
采纳的回答
Star Strider
2019-7-26
There are more problems that that one line. When I ran your code, I discovered that most of your (unfortumately-named) ‘sum’ matrix were NaN, so there was no plot. (Please do not give your variables names tthat conflict with MATLAB functions. Naming variables that conflict with MATLAB functions is termed ‘overshadowing’ and makes the function completely useless if you want to use it later. This is what your ‘sum’ variable would do.)
The loops are also unnecessary. You can take advantage of vectorization. Try this version of your code:
v0=100;
a=10;
b=5;
k=1:70;
n=(2*k)-1;
x=1:10/100:10;
y=1:5/100:5;
[X,Y,N]=meshgrid(x,y,k);
Ve = (sin(N.*pi.*X/a).*sinh(N.*pi.*Y/a)) ./ (N.*sinh(N.*pi.*Y/a));
V = (4*v0/pi) * sum(Ve,3);
It works, however it does not likely produce the sort of contour you want, so I leave that to you to sort out.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!