- 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.
Executing command only once
7 views (last 30 days)
Show older comments
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...
0 Comments
Answers (1)
Prateekshya
on 15 Oct 2024
Edited: Prateekshya
on 15 Oct 2024
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.
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!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!