How can I assign a value to a variable in the first iteration of a loop and for the rest of iterations the variable's value should be the outcome of the script?

16 ビュー (過去 30 日間)
I have a simple script that will calculate the value of the variable 'y' depending on the values of the variables 'u' and 'v':
function y = fcn(v,u)
y=0;
if (u>v)|| (u<v)
y=y+(u-v);
else
y=y;
end
For the first iteration, the initial value of 'y' should be zero. For the rest of iterations, the initial value of 'y' should be the 'y' value of the previous iteration. How can I specify it in the script?
  1 件のコメント
Erik
Erik 2015 年 7 月 23 日
I forgot to mention that I'm writing the script in a Matlab function block in Simulink.

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

回答 (1 件)

David Young
David Young 2015 年 7 月 23 日
Make y an argument to your function, and also remove unnecessary code:
function y = fcn(v, u, y)
y = y+(u-v);
end
Note that you didn't need the test, because if u is the same as v, u-v is zero.
Then in the calling code, initialise y to 0 before entry:
y = 0;
for k = 1:n
y = fcn(v, u, y);
end
  1 件のコメント
Erik
Erik 2015 年 7 月 23 日
Thank you for your answer David. I'm running this script in Simulink, so the limits of the 'for' loop will depend on the simulation time. How can I specify that?

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

カテゴリ

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