Save data after each simulation

4 views (last 30 days)
Mucenica Claudiu
Mucenica Claudiu on 26 May 2018
Answered: Rajanya on 31 Jan 2025
I am running a Matlab script which opens up a Simulink model and runs the simulation several times within a for-loop.I have a Uniform Random Number Block in my model, so the output of the Simulation will be different in each run. The problem I have is that if I run the simulation 20 times via my Matlab script, the output variable is overwritten in the workspace after each run. Is there a way to save the output variable in my workspace after each run with a different name and still be able to have my script run the simulation as many times as I want automatically?

Answers (1)

Rajanya
Rajanya on 31 Jan 2025
You can use the 'assignin' function of MATLAB for this purpose to store the output obtained from a simulation as a unique variable in the base workspace.
A sample code can look like this:
numRuns = 20;
for i = 1:numRuns
simOut = sim('exampleModel'); % a demo model containing Uniform Random Number block
%simOut = Simulink.SimulationOutput:
%output: [1x1 timeseries] - the output name is set to 'output'; default is 'yout'
%tout: [101x1 double] ...
varName = sprintf('output_%s', num2str(i)); %varName gets unique strings every simulation run
% output_1, output_2 ... output_20
assignin('base', varName, simOut.get('output')); %register the created varName in the workspace
end
For more information on the usage of 'assignin', you can refer to the documentation of the same by executing the following command from MATLAB Command Window:
doc assignin
Thanks.

Community Treasure Hunt

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

Start Hunting!