MATLAB Answers

Plotting in a Loop Always Return "Vector must be the same length"

1 view (last 30 days)
Hisyam Azmi
Hisyam Azmi on 22 Feb 2021
Commented: Hisyam Azmi on 22 Feb 2021
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
Hisyam Azmi
Hisyam Azmi on 22 Feb 2021
yes, but the problem is when I first run it, the loop doesn't calculate r from 1 to 8, as shown in this workspace result below
I used a single loop in this one like this
y = 8;
for i = 1:y
r(i) = rand + i;
plot(1:y,r,'d')
hold on
end
hold off
but, after I delete the plot command, the dimension of r is correct
then I put the line back in, it gives me a plot but it has 2 data points

Sign in to comment.

Accepted Answer

David Hill
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
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
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)

Sign in to comment.

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!