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

조회 수: 2(최근 30일)
Hisyam Azmi 2021년 2월 22일
댓글: Hisyam Azmi 2021년 2월 22일
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표시숨기기 이전 댓글 수: 1
Hisyam Azmi 2021년 2월 22일
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 댓글을 달려면 로그인하십시오.

### 채택된 답변

David Hill 2021년 2월 22일
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');
##### 댓글 수: 1표시숨기기 없음
Hisyam Azmi 2021년 2월 22일
this fixes the problem, thank you!

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

Jon 2021년 2월 22일
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표시숨기기 없음
Jon 2021년 2월 22일
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)

댓글을 달려면 로그인하십시오.

R2020b

### Community Treasure Hunt

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

Start Hunting!