MATLAB: How to add data in stateflow by using the API


I want to add a stateflow constant data by API. Is it possible?
I am doing SIL testing and would like to modify some constant data through the stateflow API.

Best Answer

  • Yes! It is possible.
    Please go through the code below to have a better understanding of the commands.
    % This script demonstrates simple example of using the statefloew API.
    % For more details about the stateflow commands please go through the
    % documentaion online
    bdclose('all'); % Close all models
    %%First create a new model
    sfnew; % Creates a new model with a new stateflow chart in it
    %%Access the model object created
    rt = sfroot;
    m = rt.find('-isa','Simulink.BlockDiagram');
    %%Access the stateflow object in the model
    ch = m.find('-isa','Stateflow.Chart');
    % Create new states A and B in stateflow
    state_A = Stateflow.State(ch);
    state_A.Name = 'A';
    state_A.Position = [80 120 90 60];
    state_B = Stateflow.State(ch);
    state_B.Name = 'B';
    state_B.Position = [240 120 90 60];
    % Create a transition
    trans_A2B = Stateflow.Transition(ch);
    trans_A2B.Source = state_A;
    trans_A2B.Destination = state_B;
    trans_A2B.SourceOClock = 3;
    trans_A2B.DestinationOClock = 9;
    % Add a default transition to state A
    default2A = Stateflow.Transition(ch);
    default2A.Destination = state_A;
    default2A.DestinationOClock = 0;
    %%Add input/output and parameters and constants to the chart
    % Add an input in1
    data_in = Stateflow.Data(ch);
    data_in.Scope = 'Input';
    data_in.Name = 'in1';
    % Add an output out1
    data_out = Stateflow.Data(ch);
    data_out.Scope = 'Output';
    data_out.Name = 'out1';
    % Add a constant Param1
    data_param = Stateflow.Data(ch);
    data_param.Scope = 'Parameter';
    data_param.Name = 'Param1';
    % Add a constant Const1
    data_const = Stateflow.Data(ch);
    data_const.Scope = 'Constant';
    data_const.Name = 'Const1';
    data_const.Props.InitialValue = '17'; % => Change the constant initial value here
    % Open the stateflow chart for view
    %%Save the model with any name you want
    Also, some type of variables like the constant type can only be set before the simulation starts. If you are trying to dynamically change the read-only variables during the simulation for the SIL then, you might get an error. Please see relevant documentation linked below for read-only variable types:
    Manage Data::
    Set Data Properties: