Plotting in a Loop Always Return "Vector must be the same length"
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.
2 Comments
KALYAN ACHARJYA
on 22 Feb 2021
It clearly mentioned in the error message, if you wish to plot two vectors, both vectors length must be same.
Please check the length of r, whereas 1:y length is 8
Accepted Answer
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');
More Answers (1)
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
1 Comment
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)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!