Plotting every iteration of a while loop with multiple if statements

조회 수: 12 (최근 30일)
Sean Sullivan
Sean Sullivan 2018년 3월 22일
댓글: VBBV 2022년 3월 6일
I have a while loop that has 3 if statements within it. For example while x>0 && x<5 and 3 if statements solving for y with different formulas within that range of 0-5. I need to plot every iteration of that range and cannot figure out how to do so.
Thanks!
  댓글 수: 3
Sean Sullivan
Sean Sullivan 2018년 3월 22일
편집: James Tursa 2018년 3월 22일
x = 0.5;
while x>0 && x<6
x = x+0.5;
if x <4
syms y
eqn = y==2*x;
y = solve(eqn,y)
end
if x>4
syms y
eqn = y==0.5*x;
y = solve(eqn,y)
end
if x == 4
syms y
eqn = y==5*x;
y = solve(eqn,y)
end
end
VBBV
VBBV 2022년 3월 6일
x = 0.5;
while x>0 && x<6
x = x+0.5;
if x<4
syms y
eqn = y==2*x;
y = solve(eqn,y);
plot(x,y,'bo','MarkerFaceColor','b')
hold on
end
if x>4
syms y
eqn = y==0.5*x;
y = solve(eqn,y)
plot(x,y,'ro','MarkerFaceColor','r')
hold on
end
if strcmp(x,4)
syms y
eqn = y==5*x;
y = solve(eqn,y)
plot(x,y,'yo','MarkerFaceColor','y')
end
end
y = 
y = 
y = 
y = 
3

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

답변 (1개)

Ameer Hamza
Ameer Hamza 2018년 4월 24일
From our code in the comment , it appears that you don't need solve() function. You just have one equation and you already know the value of independent variable x. You can write your code as
l = line;
l.XData = [];
l.YData = [];
x = 0.5;
while x>0 && x<6
x = x+0.5;
if x <4
y = 2*x;
l.XData = [l.XData x];
l.YData = [l.YData y];
end
if x>4
y = 0.5*x;
l.XData = [l.XData x];
l.YData = [l.YData y];
end
if x == 4
y = 5*x;
l.XData = [l.XData x];
l.YData = [l.YData y];
end
end
This will also plot values of x and y.

카테고리

Help CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by