How to save to mat file sequentially using a loop and simout?

7 visualizaciones (últimos 30 días)
Gustavo Araujo
Gustavo Araujo el 10 de Feb. de 2021
Respondida: Harsh el 20 de Feb. de 2025 a las 6:24
Hi everyone!
I'm getting stuck on a simple part of my code. I have a simulink simulation that exports to Workspace two outputs: Fault and Ir. I'm trying to do a loop to automatically run my simulation and save these outputs. Here's the code:
for i = 1:100
simOut(i) = sim('mymodel');
filename1(i) = 'Fault.mat(i)';
save(filename1)
filename2(i) = 'Ir.mat(i)';
save(filename2)
end
But I'm getting:
Unable to perform assignment because the indices on the left side are not compatible with the size of the right.
How to solve this?
Thank you in advance!

Respuestas (1)

Harsh
Harsh el 20 de Feb. de 2025 a las 6:24
Hi Gustavo,
The output from “sim” function is an object which should be stored in a cell array. Furthermore the “filename1(i)” and “filename2(i)” in your code will just be strings with values as “Fault.mat(i)” and “Ir.mat(i)” respectively. To dynamically save files depending on the iteration you should use sprintf” instead. Also the variable name to save needs to be given as input in the “save” function.
Below is the code to save the results from your simulation model:
simOut=cell(100,1);
filename1=[];
filename2=[];
for i = 1:100
% Run the simulation
simOut{i} = sim('mymodel');
% Extract outputs
Fault = simOut{i}.Fault;
Ir = simOut{i}.Ir;
% Save with proper dynamic filename
filename1 = sprintf('Fault_%d.mat', i);
save(filename1, 'Fault');
filename2 = sprintf('Ir_%d.mat', i);
save(filename2, 'Ir');
end

Categorías

Más información sobre Interactive Model Editing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by