필터 지우기
필터 지우기

My if statement nestled in for loop isn't working

조회 수: 1 (최근 30일)
d c
d c 2017년 3월 3일
댓글: d c 2017년 3월 4일
When i run the following code, it calculates values x and y only for M=3. I want to calculate x and y for each of M=1,2,3.
%
x(1)=0;
y(1)=1;
for M=1:3
if M==1
h=0.01;
elseif M==2
h=0.1;
elseif M==3
h=0.5;
end
N=1/h;
for i=1:N
x(i+1)=x(i)+h;
y(i+1)=y(i)+h*(x(i)+y(i));
end
end
Also, since M=3 this would imply h=0.5 (and so N=2) and thus x and y would be 1x3 vectors. However, this is not the case; x and y are returned as 1x101 vectors which suggests it is using the value h=0.01. I'm really lost on why this happens, any help would be appreciated.

채택된 답변

GEEVARGHESE TITUS
GEEVARGHESE TITUS 2017년 3월 3일
I have just modified the code to get the output, and the final values for different values of M are stored in a cell.
clear all;
for M=1:3
clear x;
clear y;
x(1)=0;
y(1)=1;
if M==1
h=0.01;
elseif M==2
h=0.1;
elseif M==3
h=0.5;
end
N=1/h;
for i=1:N
x(i+1)=x(i)+h;
y(i+1)=y(i)+h*(x(i)+y(i));
end
x1{M}=x;
y1{M}=y;
end
  댓글 수: 1
d c
d c 2017년 3월 4일
Many thanks, I can work with this now. :)

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

추가 답변 (0개)

카테고리

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