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

1 回表示 (過去 30 日間)
Hisyam Azmi
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 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2021 年 2 月 22 日
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
Hisyam Azmi
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
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 件)

Jon
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
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)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by