Djamillah
Djamillah

Reputation: 289

Plot Lines Inside for-loop In Matlab

I'm using a for-loop in order to plot the 'track' from a particle that moves in a specific way. When I try to plot lines inside the for-loop I only get dots.

This is my code:

a = [0];
b = [0];

for k = 1:10
    r = randn(1,2);
    a = a+r(1);
    b = b+r(2);
    k = k+1;

    plot(a,b,'-r')
    pause(1)
end

I've read other questions about this here at stackoverflow but those answers doesn't work for me.

Upvotes: 0

Views: 113

Answers (1)

Nathan Fellman
Nathan Fellman

Reputation: 127428

You have a few bugs here. First of all, this:

for k = 1:10           <--------
    r = randn(1,2);
    a = a+r(1);
    b = b+r(2);
    k = k+1;           <--------

    plot(a,b,'-r')
    pause(1)
end

The for statement will already increment k. There's no need to do it manually.

Second of all, you basically want to create the arrays a and b and then plot them:

a = [0];
b = [0];
for k = 1:10
    r = randn(1,2);
    a = [a[1:end], a[end] + r(1)];
    b = [b[1:end], b[end] + r(2)];

end
plot(a,b,'-r')

This should plot your random arrays.

Upvotes: 1

Related Questions