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

6 次查看(过去 30 天)
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!

回答(1 个)

Harsh
Harsh 2025-2-20,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

类别

Help CenterFile Exchange 中查找有关 Interactive Model Editing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by