Using previous values to calculate next one in a for loop

Hi, I have a matlab code to calculate agitation speed in my reactor. It uses 2 previous values of Dissolved oxygen and the previous agitation speed. My question is, I know that I can't use (i-1) in order to get the previous value. So how can I do it? Should I use (i+1)?

 Accepted Answer

If you begin with ‘i’ that is at least 3, and you have already defined two previous values for your variables, you can use (i-1) and (i-2).

4 Comments

Hi Star Strider,
thanks for your answer, I tried it but it didn't work. I took a screenshot of the code. I may have done something wrong.
My pleasure.
You have to have defined at least two values for ‘OOP’, ‘AgitMedP’ (and any other variables you want to define previous values for), so they are all vectors. Then begin with ‘i’ at least 3.
You also cannot use ‘OOP’ and ‘OOP(i-1)’ in the same expression, because ‘OOP’ is a vector by definition, and will create a vector output, not a scalar. This will throw an error since you are assigning it to a scalar value. Only use single scalar elements of your vectors in the ‘AgitMedP(i)’ calculation. It is a scalar, and will only accept scalar values.
I would do something like this (although I have no idea what your arrays are):
OOP = dados(1:2, 4);
AgitMedP = dados(1:2, 2);
for i = 3:100
...
end
I tried to reformulate the code, but I got this error message: Attempted to access ODP(4); index out of bounds because numel(ODP)=3.
From your description of what you are doing, you will need to add elements to your vectors as you update them in each iteration. So, each time, you need to calculate and store values for ‘OOP’ as well as any others.
If you already have all 100 values for ‘OOP’, refer to elements of the vector in your loop. For example, define ‘OOP’ before your loop as:
OOP = dados(:,4);

Sign in to comment.

More Answers (1)

Thanks Star Strider! It worked!! thanks so much for your help!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!