Executing command only once

조회 수: 5 (최근 30일)
Meral
Meral 2011년 8월 23일
편집: Prateekshya 2024년 10월 15일
Hello everyone
I wrote a program in Embedded Matlab Function block in Simulink. In this block I have to define some variables as 0 (zero) at beginning but it must be 0 only at first. Then it is calculated in the program. So I want to execute these defination commands only once. Embedded Matlab Function program is very similar to .m script file. Is there a way to execute only once? Thanks in advice...

답변 (1개)

Prateekshya
Prateekshya 2024년 10월 15일
편집: Prateekshya 2024년 10월 15일
Hello Meral,
In Simulink, when you want to execute certain initialization code only once within an Embedded MATLAB Function block (now called a MATLAB Function block), you can achieve this by using persistent variables. Persistent variables retain their values between function calls, which is useful for storing state information across multiple executions of the block. Let us see how it can be done.
  • Define Persistent Variables: Use the persistent keyword to define variables that should retain their values between calls to the function.
  • Initialize Only Once: Check if the persistent variable is empty, which indicates that it's the first execution, and perform the initialization only in this case.
  • Update Variables: After the first execution, update the persistent variables as needed during subsequent calls.
Here is an example of how you can implement this in a MATLAB Function block:
function y = myFunction(u)
% Declare persistent variables
persistent myVar;
% Initialize persistent variables only once
if isempty(myVar)
myVar = 0; % Initial value set to 0
end
% Your calculation or update logic
myVar = myVar + u; % Example of updating the variable
% Output the current value of myVar
y = myVar;
end
To know more about the persistent variables, please go through the following documentation link: https://www.mathworks.com/help/matlab/ref/persistent.html
I hope this helps!

카테고리

Help CenterFile Exchange에서 Simulink Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by