Using previous value to get the next in for loop

Hi guys,
I have what I believe is a simple problem but I cannot manage to get to work!
I have a (6003 x 1) vector of u-values. I want to create a vector of y-values which are defined using the previous value and its corresponding u-value as such:
h=0.1;
y(1) = 0
y(2) = y(1) + h.*u(1)
y(3) = y(2) + h.*u(2) ... etc.
At the moment, my loop is defined as such:
h=0.1;
y(1) = 0;
for k=2:6003
y(k) = y(k-1) + h.*u(k-1)
end
But this makes my command window seemingly run forever. How do I correct this code? Any help is much appreciated!

 採用された回答

Stephan
Stephan 2021 年 5 月 12 日
編集済み: Stephan 2021 年 5 月 12 日

1 投票

The semicolon operator supresses outputs to the command window:
h=0.1;
y(1) = 0;
for k=2:6003
y(k) = y(k-1) + h.*u(k-1);
end

3 件のコメント

Stephen23
Stephen23 2021 年 5 月 12 日
"But the much better news for you is that you dont need a for loop"
True, but you do realize that your "don't need a loop" code uses data from the loop?
Did you check the output values?
Stephan
Stephan 2021 年 5 月 12 日
編集済み: Stephan 2021 年 5 月 12 日
oops ;-) - corrected - thank you @Stephen Cobeldick
Joel Childs
Joel Childs 2021 年 5 月 12 日
Thank you both of you!

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

その他の回答 (1 件)

Stephen23
Stephen23 2021 年 5 月 12 日
編集済み: Stephen23 2021 年 5 月 12 日

2 投票

"But this makes my command window seemingly run forever."
So far no one has actually addressed why your code is inefficient, in particular:
  1. lack of array preallocation before the loop,
  2. pointless printing to the command window.
Your code will be quite efficient once you deal with both of those, for example:
h = 0.1;
n = 6003;
y = zeros(1,n);
for k = 2:n
y(k) = y(k-1) + h.*u(k-1);
end

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

製品

リリース

R2021a

質問済み:

2021 年 5 月 12 日

コメント済み:

2021 年 5 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by