for-end loop with increment and movie

My code plots a route taken based on random numbers and takes frames at intervals of 1000 steps. However the total number of steps won't always be divisible by 1000, is there a way of always plotting the final frame in the set?
here's my code at the moment
for j=1:1000:k
M((j-1)/1000+1) = getframe;
plot(x(1:(j+1)),y(1:(j+1)))
axis equal
if x(j+1)==H1 && y(j+1)==H2
break
end
end
hold off
movie(M)

Answers (1)

First, make sure to use drawnow to refresh the graphics queue between loop iterations.
Second, use the for-loop variable as the index and generate the other values from it (i.e. inverse to what you've done). Then run it from 1-however_many
Third, use min() to saturate the variable at the maximum ends of things so you don't get out of dimension errors. e.g. if j = 100001 and the max you have is 100000, use min(j,10000) so you don't over step the number of elements.

1 Comment

Thanks for your help.
We'd decided against drawnow because it seemed quicker to generate all the values first and then plot them all at once.
I don't know what you mean by the index, we've been taught some basic commands but nothing has really been explained to us. However if you mean to use the values of j to create the values of k, there's another for loop which creates those.
Here's the full code if that makes more sense;
clear all
H1 = input('Please enter a co-ordinate for the drunk mans Home in the x-direction');
H2 = input('Please enter a co-ordinate for the drunk mans Home in the y-direction');
while H1==0 && H2==0
disp('The pub is not the drunk mans Home')
H1 = input('Please enter a co-ordinate for the drunk mans Home in the x-direction');
H2 = input('Please enter a co-ordinate for the drunk mans Home in the y-direction');
end
N = input('Please enter a value between 10 and 5,000,000 for the number of steps');
while N<10||N>5000000
disp('Sorry, you did not enter a valid number please try again')
N = input('Please enter a value between 10 and 5,000,000 for the number of steps');
end
x = 0;
y = 0;
x = zeros(1,N);
y = zeros(1,N);
for k=1:N
J = rand;
if J<0.25;
x(k+1)=x(k)+1;
y(k+1)=y(k);
elseif J>=0.25 && J<0.5;
x(k+1)=x(k);
y(k+1)=y(k)+1;
elseif J>=0.5 && J<0.75;
x(k+1)=x(k)-1;
y(k+1)=y(k);
else
x(k+1)=x(k);
y(k+1)=y(k)-1;
end
if x(k+1)==H1 && y(k+1)==H2
steps = k+1;
break
end
end
if k<N
disp ('The Drunk man arrived home')
else disp('The Drunk man does not arrive home')
end
disp('Number of Steps taken is')
disp(k)
plot(H1,H2,'mp')
text(H1,H2,'\leftarrowHome');
hold on
plot(0,0,'bs')
text(0,0,'\leftarrowEchos');
hold on
for j=1:1000:k
M((j-1)/1000+1) = getframe;
plot(x(1:(j+1)),y(1:(j+1)))
axis equal
if x(j+1)==H1 && y(j+1)==H2
break
end
end
hold off
movie(M)

Sign in to comment.

Asked:

on 10 May 2012

Community Treasure Hunt

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

Start Hunting!