Using previous value to get the next in for loop
215 views (last 30 days)
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:
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:
y(1) = 0;
y(k) = y(k-1) + h.*u(k-1)
But this makes my command window seemingly run forever. How do I correct this code? Any help is much appreciated!
More Answers (1)
Stephen23 on 12 May 2021
Edited: Stephen23 on 12 May 2021
"But this makes my command window seemingly run forever."
So far no one has actually addressed why your code is inefficient, in particular:
- lack of array preallocation before the loop,
- 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);