Plotting every iteration of a while loop with multiple if statements
10 views (last 30 days)
Show older comments
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 Comments
VBBV
on 6 Mar 2022
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
Answers (1)
Ameer Hamza
on 24 Apr 2018
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.
0 Comments
See Also
Categories
Find more on Calculus 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!