how to manage 'Switch case' and persistent variables in Matlab Function Block in Simulink?
Show older comments
Dear community,
I want to simulate a model in Simulink using Matlab Function. The model has two inputs and two outputs. And there are several variables in the Matlab function code.

In the first part of the code, I want to initialize the variables. And in the second part I want to calculate the outputs depending on the inputs and the variables. Some variables are persistent.
I tried two solutions, but they are note working.
- The sketch of the code is as follows:
function [output1,output2] = fcn(flag,input1, input2)
persistent a b
switch flag
case 1
% load variables from .mat file, for example a,b,c,d,x and y
% some allocations
% do it only once for Initialization.
case 2
% Regular time step
a = a*x+c;
b = b*y+d;
output1 = a*input1;
output2 = b*input2;
end
I want to know how to use the switch statement. What to put in the flag? Is it a vector or a Step from Simulink?
- I tried to use the InitFcn callback in the Matlab function block properties. But it is not working. I can see the variables in the base workspace, but Simulink is giving me an error that the variables are not defined. I tried to define the variable as global but is also not working. In this solution I also tried to put all the variables in one object and to enter it as a parameter to the block as described here (https://fr.mathworks.com/help/simulink/ug/parameter-arguments-in-matlab-function-block-functions.html). But I do not know how to manage the persistent variables.
I need your help to find the best solution.
Thanking you, Amjad
Accepted Answer
More Answers (0)
Categories
Find more on Event Functions 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!