1 view (last 30 days)

Show older comments

So I was doing some little experimenting with MATLAB R2020b and R2019b and I encountered an error while trying to plot a variable inside a for loop, here's the code

x = 2;

y = 8;

for n = 1:x

for i = 1:y

r(n,i) = rand + i;

plot(1:y,r,'d')

hold on

end

hold off

end

when I ran it, it gives the following error, and in the workspace variable r is a 1x2 matrix (shouldn't it be 1x8 in the 2nd loop?)

I've tried to delete the line, use clear all on the command window, and then rewrite the line exactly as it is then it works but there are 3 data points instead of 2

any idea what might caused the errors? Thank you.

David Hill
on 22 Feb 2021

Why plot in the loop?

for n = 1:x

for i = 1:y

r(n,i) = rand + i;

end

end

plot(1:y,r,'d');

Jon
on 22 Feb 2021

Since r is not preallocated to a 2 by 8 matrix it gets built up as it goes.

The first time through your loop when you assign r(n,i), n =1 and i = 1 so r(n,i) is just a scalar. The second time you assign r(n,i), n still equals 1 but now i equals 2 so r(n,i) is no a 1 by 2 row vector, and so on

Jon
on 22 Feb 2021

As I now see David has posted, you can just build the whole matrix and then plot the two rows.

It is good practice though to proceed your loop with a "preallocation" of r so in your case.

This will store the matrix more efficiently in memory, and also will guard against the case that you already have some variable r in you workspace and then just reassign some of its elements.

r = zeros(x,y)

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

Start Hunting!