Reputation: 1837
I want to check how some block parameter affect the results in my simulation.
I use a for loop to change this parameter however it works pretty slow.
mdl_name='Gains';
open_system(mdl_name);
for K1 = 1:2
for K2 = 1:2
for K3 = 0.1:0.1:2
set_param([mdl_name,'/Tfn'],'Numerator',mat2str(50),'Denominator',mat2str([20]));
set_param([mdl_name,'/K1'],'Gain',mat2str(K1));
set_param([mdl_name,'/K2'],'Gain',mat2str(K2));
set_param([mdl_name,'/K3'],'Gain',mat2str(K3));
mdl_name='PWM_Gains';
open_system(mdl_name);
Data = sim(mdl_name,'StartTime','40','StopTime','85','FixedStep',num2str(dt));
Delta_PWM{i} = Data.get('Delta_PWM').signals.values;
Gains{i} = [K1,K2,K3];
i = i + 1
end
end
end
Is there any more efficient way to solve it?
Thank you
Upvotes: 0
Views: 1316
Reputation: 6863
Use parsim
.
You can use load_system
instead of open_system
to avoid opening simulink. You probably only have to call it once, before the for loop, and not every iteration.
If it still takes too long, try larger stepsize (or variable, to be determined by the ode solver), or a larger step size in the changing parameters.
Example using parsim:
% load model
mdl_name='Gains';
load_system(mdl_name);
% parameter to simulate
K1 = 1:2;
K2 = 1:2;
K3 = 0.1:0.1:2;
% create matrix with all combinations
[k1, k2, k3] = ndgrid(K1, K2, K3);
Gains = [k1(:), k2(:), k3(:)];
% Create an array of SimulationInput objects and specify the sweep value for each simulation
numSims = size(Gains,1);
simIn(1:numSims) = Simulink.SimulationInput(model);
% setup models
for idx = 1:numSims
% get Gains
K1 = Gains(idx,1);
K2 = Gains(idx,2);
K3 = Gains(idx,3);
% set Gains
simIn(idx) = simIn(idx).setBlockParameter([mdl_name,'/Tfn'],'Numerator',mat2str(50),'Denominator',mat2str([20]));
simIn(idx) = simIn(idx).setBlockParameter([mdl_name,'/K1'],'Gain',mat2str(K1));
simIn(idx) = simIn(idx).setBlockParameter([mdl_name,'/K2'],'Gain',mat2str(K2));
simIn(idx) = simIn(idx).setBlockParameter([mdl_name,'/K3'],'Gain',mat2str(K3));
% set simulation parameters
simIn(idx) = simIn(idx).setModelParameter('StartTime','40', 'StopTime','85','FixedStep',num2str(dt));
end
% Simulate the model
simOut = parsim(simIn);
Upvotes: 1