How declare a variable only once in a matlab function block and then use the previous value the nex time the function is used?

22 ビュー (過去 30 日間)
I am using the matlab function block in simulink. I need it to continuously read its inputs and change its outputs. The problem is that I must declare my start position as zero. Then my function runs and increments as desired. THEN it seems to enter the function again and reset to zero (as it would). I need to declare the variable to zero the very first time through the function then all times after use the value that it generated before. See code below:
function y = fcn(sEMG5,sEMG6)
%#codegen
% %set original servo positions to zero
% servo2=0;
% servo3=0;
% servo4=0;
% servo5=0;
%incrememt servo position when threshold is met
if sEMG5 > 150
servo2 = servo2+3;
elseif sEMG6 > 150
servo2= servo2-3;
end
%keep servo position in allowable range
if servo2 > 180
servo2 = 180;
elseif servo2 < 0
servo2 = 0;
else
servo2=servo2;
end
y = servo2;
So my problem is how to declare servo2 as zero once and then use the value that y was all successive times through. Thanks!

採用された回答

Ryan Livingston
Ryan Livingston 2014 年 7 月 9 日
You could also use a persistent variable inside your MATLAB function block:
function y = fcn(sEMG5,sEMG6)
%#codegen
persistent servo2;
% set original servo positions to zero the
% first time this function is invoked
if isempty(servo2)
servo2=0;
end
% Use servo2 here
...
  2 件のコメント
Daniel Sluder
Daniel Sluder 2014 年 7 月 9 日
Thanks. My colleagues want to keep the simulink model as simple as possible
subhahsay shetty
subhahsay shetty 2018 年 9 月 30 日
what if we want to initialize and then update the values. Can we do that??

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

その他の回答 (1 件)

Anthony Poulin
Anthony Poulin 2014 年 7 月 9 日
Is it possible for you to have one more input and one more output? What I suggest is to do like the image below:
You do not work with a variable but with an input (u2) that you update and affect to the output (y2). With a unit delay you have your output, in input the next simulation step u2(z) = y2(z-1). (You configure your unit delay with the initial value to 0)

カテゴリ

Help Center および File ExchangeEvent Functions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by