When does one need to index for plotting

1 回表示 (過去 30 日間)
am
am 2019 年 3 月 28 日
コメント済み: am 2019 年 3 月 28 日
I refer to this question:
I previously never indexed when I filled with values in a while loop and the values were saved in the vector.
But in that case I needed to do :
iterations(iter) = iter
error(iter) = norm(x-x_ref)
to make sure the values were saved in the vector and adapt automatically.
Can someone explain why is that, when manipulating vectors, sometimes you need to iterate with an index and sometimes not?

採用された回答

Walter Roberson
Walter Roberson 2019 年 3 月 28 日
You do not need indexing when you have vectorized code. For example,
x = linspace(0, 2*pi, 500);
y = sin(x) .* cos(x.^2);
plot(x, y);
All of the values are produced at the same time.
You do need indexing when you are producing only part of the answer at a time. For example,
x = linspace(0, 2*pi, 500);
y = zeros(size(x));
for K = 1 : numel(x)
y(K) = sin(x(K)) .* cos(x(K).^2);
end
  2 件のコメント
am
am 2019 年 3 月 28 日
Thank you.
So I need indexing in every loop?
Walter Roberson
Walter Roberson 2019 年 3 月 28 日
No. Consider
t = linspace(0, 2*pi, 500);
x = zeros(size(t));
for K = 1:2:5
x = x + sin(2*pi*t*K);
end
This is a loop, but each iteration of the loop produces a full vector of results and so does not need any indexing.

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

その他の回答 (1 件)

am
am 2019 年 3 月 28 日
I am sorry, I don't understand. Does each iteration rewrites x?
  5 件のコメント
Walter Roberson
Walter Roberson 2019 年 3 月 28 日
The first line creates a 15 x 2 matrix of normally distributed random numbers (with mean 0 and standard deviation 1)
The second line calculates the sine of the first column and replaces the first column with those sines. Indexing was needed on the right side of the = in order to fetch only the first column, and indexing was needed on the left side of the = in order to assign to only the first column.
The third line calculates the exponential of the second column and replaces the second column with those exponentials. Indexing was needed on the right side of the = in order to fetch only the second column, and indexing was needed on the left side of the = in order to assign to only the second column.
The end result is 15 x 2.
am
am 2019 年 3 月 28 日
Thank you, it's clearer.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by