Plot the same function several times in one go (Random walk)?

1 回表示 (過去 30 日間)
Delshad Ayoubi
Delshad Ayoubi 2017 年 10 月 11 日
コメント済み: Rik 2017 年 10 月 11 日
clear
clc
==================
N = 10; % number of steps.
M = 10;
x_t(1) = 0;
for n = 1:N
a = sign(randn);
x_t(n+1) = x_t(n) + a;
end
plot(x_t);
xlabel('t'), ylabel('x_t'), title('randomwalk');
Someone already helped me with this task but he rewrote the entire code as a means of vectorizing it, is there any way I could plot the same function several times while retaining the previous plot, without changing too much of my code? I'm not sure how to progress beyond this stage since it doesn't do anything when i implement
hold on

採用された回答

Rik
Rik 2017 年 10 月 11 日
You should always include a link to the old question, so people can look there for context. Of course it is always best to use vectorized code. It is a bad idea to refuse that kind of speed increasing measures. But if you are adamant about not using that other solution, just wrap this code in a for loop if you want to repeat it.
clear variables
clc
==================
N = 10; % number of steps.
M = 10;
for m=1:M
x_t(1) = 0;
for n = 1:N
a = sign(randn);
x_t(n+1) = x_t(n) + a;
end
plot(x_t);hold on
end
xlabel('t'), ylabel('x_t'), title('randomwalk');
  2 件のコメント
Delshad Ayoubi
Delshad Ayoubi 2017 年 10 月 11 日
Thanks, that the exact answer I wanted. Is there a distinct disadvantage if I continue in not using vectorised scripts? Can you try to create a simple, easy to understand vectorised script of what you did above?
I'm not used in using that method but would like to practice.
Rik
Rik 2017 年 10 月 11 日
The plot function accepts matrix inputs (to plot multiple lines), and what you are essentially doing in the loop is calculating a cumulative sum of the output of randn. Because randn can also output a matrix, you can put those together.
So a vectorized solution would combine randn, sign, cumsum and plot. As far as I can see, you will not need any more functions (except xlabel, ylabel and title of course).
It is always best to try thing for yourself, so see if you can find the solution yourself now.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by