How to combine several pieces of code in a For Loop?!

6 views (last 30 days)
Hello All!
I have a question regarding a for loop, or if you think there is a better way to write this code. I have three different codes below and i am trying to compile them into a for loop. I attempted to do it below the three codes (they are labeled). My goal is to plot the first code, then "erase it" and draw the next one, etc. etc. My overall goal is that I am trying to draw a 2-d image of the spring part of a spring mass. I already have the mass part moving and now I am working on the spring. I feel as if a for loop would be useful for this, but I cannot figure out how to write it.
Thanks for all your help! code below:
%%
x=[0:.2:1]
y=[0,2,0,2,0,2]
plot(x,y,'b','linewidth',2)
hold on
axis([-2 10 -2 5])
%%
x=[0:.4:2]
y=[0,2,0,2,0,2]
plot(x,y,'b','linewidth',2)
hold on
axis([-2 10 -2 5])
%%
x=[0:.6:3]
y=[0,2,0,2,0,2]
plot(x,y,'b','linewidth',2)
hold on
axis([-2 10 -2 5])
%%
x=[0:.8:4]
y=[0,2,0,2,0,1]
plot(x,y,'b','linewidth',2)
hold on
axis([-2 10 -2 5])
%My attempt at a for loop:
x=1
for k=.4:.4:10
x(k)=[0,0+k,0,0+k,0,0+k]
y=[0,1,0,1,0,1]
hold on
axis([-2 20 -2 5])
plot(x(k),y,'b','linewidth',2)
end
  2 Comments
William Fantin
William Fantin on 13 May 2019
Edited: William Fantin on 13 May 2019
Just tried something probably more realistic for my for loop that i just figured out. Does anyone have anymore suggestions on how to make it better?
Thanks!
for k=.2:.2:2
x=[0,0+k,2*k,3*k,4*k,5*k,6*k,7*k,8*k,9*k]
y=[0,2,0,2,0,2,0,2,0,1]
hold on
axis([-2 20 -2 5])
plot(x,y,'b','linewidth',2)
pause(.2)
plot(x,y,'w','linewidth',2)
end
for k=2:-.2:.2
x=[0,0+k,2*k,3*k,4*k,5*k,6*k,7*k,8*k,9*k]
y=[0,2,0,2,0,2,0,2,0,1]
hold on
axis([-2 20 -2 5])
plot(x,y,'b','linewidth',2)
pause(.2)
plot(x,y,'w','linewidth',2)
end
Luna
Luna on 13 May 2019
What is your actual y in each plot? 0,2,0,2,0,2 always? In for loop it seems [0,1,0,1,0,1].
And how long do you want to hold the lines then erase?

Sign in to comment.

Answers (1)

Luna
Luna on 13 May 2019
Hello William,
Just by changing your y array it works.
Try this:
xStart = 0;
xFinishArray = 1:4;
y = [0,2,0,2,0,2];
hFig = figure;
for i = 1:numel(xFinishArray)
temp_x_to_plot = linspace(xStart,xFinishArray(i),numel(y));
plot(temp_x_to_plot,y,'b','linewidth',2);
axis([-2 20 -2 5]);
pause(1);
end

Categories

Find more on Loops and Conditional Statements 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!