0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.