Nested for loop for contour plotting of Laplace equation
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Star Strider
on 26 Jul 2019
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.
2 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!