remi
remi

Reputation: 566

Save complete Simulink SimState periodically or each time a predicate is true during a simulation

I am trying to find a way to generate multiple intermediate SimState objects during a Simulink sim run, at predefined instants, letting the simulation run to its specified StopTime.

The documentation says it is only possible to save the complete final state, but maybe there's a way ?

Upvotes: 0

Views: 657

Answers (1)

Phil Goddard
Phil Goddard

Reputation: 10772

If you need to run the model from the Simulink user interface then you'd need to write a custom block that would pause the model, save the simstate and then restart the simulation, at specific intervals. But the easier approach would be to run the model from the command line, doing something like the following:

% Define stop times and preallocate a cell array to save the simstates
stop_times = 1:10; % one second intervals upto 10 seconds
sim_states = cell(1,numel(stop_times));

% Run the model in a loop, saving the simstate at the required times
for tdx = 1:numel(stop_times)

   if tdx == 1
      % First simulation
      sim_out = sim('mdl_name', 'StopTime', num2str(stop_times(tdx)), 'SaveFinalState', 'on', ...
             'LoadInitialState', 'off', 'SaveCompleteFinalSimState', 'on',...
             'FinalStateName', 'final_simstate');
   else
      % subsequent simulations
      assignin('base', 'new_simstate', sim_states{tdx-1});
      sim_out = sim('mdl_name', 'StartTime', num2str(stop_times(tdx-1)),...
             'StopTime', num2str(stop_times(idx)), 'SaveFinalState', 'on', ...
             'LoadInitialState', 'on','InitialState', 'new_simstate',...
             'SaveCompleteFinalSimState', 'on',...
             'FinalStateName', 'final_simstate');
   end

   % store the simstate
   sim_states{tdx} = sim_out.get('final_simstate');
end

The above code assumes variables are loaded form the Base workspace but can easily be modified to get it from the model workspace or a function workspace.

Upvotes: 2

Related Questions