for loops not working

조회 수: 1 (최근 30일)
sriram amarnath
sriram amarnath 2019년 6월 24일
댓글: sriram amarnath 2019년 6월 24일
The below code is to calculate the modes on a plate. The for loops are not using all the values of m & n
% Modes on a plate
Lx=0.286; % length of plate(m)
Lz=0.198; % breadth of plate(m)
for m = 1:1000 % mode numbers
for n = 1:10
func=((n.*pi)./Lx).^2 +((m.*pi)./Lz).^2;% summation function n=1:10 & m= 1:1000
end
end
  댓글 수: 2
dpb
dpb 2019년 6월 24일
I'm sure the loop runs 10,000 times--only you don't do anything inside the loop except write over the same variable with each computed value in succession so all you get in the end is the very last value.
sriram amarnath
sriram amarnath 2019년 6월 24일
So how do i get a matrix of every value?

댓글을 달려면 로그인하십시오.

채택된 답변

madhan ravi
madhan ravi 2019년 6월 24일
편집: madhan ravi 2019년 6월 24일
The same goal can be achieved trivially using meshgrid() or ndgrid() without a loop:
% Modes on a plate
Lx=0.286; % length of plate(m)
Lz=0.198; % breadth of plate(m)
n=10;
m=1000;
[Y,X]= ndgrid(1:m,1:n);
func=(X*pi/Lx).^2 +(Y*pi/Lz).^2;
But the modication in your code is as follows:
func = zeros(1000,10); % before loop
func(m,n) = ... %just add (m,n) next to func inside the loop
  댓글 수: 1
sriram amarnath
sriram amarnath 2019년 6월 24일
Thanks madhan ravi your a saviour!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2019년 6월 24일
"The MATLAB way" is to avoid the loops altogether...
N=10; M=1000;
[X,Y]=meshgrid([1:N],1:M]);
func=(X*pi/Lx).^2 +(Y*pi/Lz).^2;

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by