Run a simulink model from a nested function in matlab code and save data
显示 更早的评论
Hello everyone!
I'm simulating an electric circuit model with Simulink/Simscape. I want to estimate the parameters of this circuit by comparing the real voltage (taken from measurements) with the simulated voltage. I measure the voltage with a voltage sensor and connect its output to a "To workspace". When I run the model with known values of the parameters, the vector V_sim is shown to the base workspace thanks to "To workspace" block.
My main problem is that in my code I use this nested function
function out = mySimulation(x)
assignin('base', 'R0', x(1));
assignin('base', 'R1', x(2));
assignin('base', 'R2', x(3));
assignin('base', 'R3', x(4));
assignin('base', 'C0', x(5));
assignin('base', 'C1', x(6));
assignin('base', 'C2', x(7));
assignin('base', 'C3', x(8));
out= sim('RC_3branch');
assignin('base', 'V_sim', V_sim);
end
The command "assignin('base', 'V_sim', V_sim);" allows the function to export "V_sim" from the local workspace to the base one.
I call the function "out=mySimulation(x)" in another nested function of the code that is my objective function, the one I want to minimize in order to define the right set of parameters. The function is:
function y = objectiveFunction(x,V_real)
out = mySimulation(x);
y= sum((V_sim - V_real).^2);
end
My initial idea was to call "out=mySimulation(x)" that, since how it is defined, should give as output "V_sim" and the object function should measure sum((V_sim - V_real).^2).
This is not happening, when the code arrives at objectiveFunction, it stops running because it does not find any "V_sim" variables.
I fixed it in this way:
function y = objectiveFunction(x,V_real)
out = mySimulation(x);
out= sim('RC_3branch');
assignin('base', 'V_sim', V_sim);
y= (sum((V_sim - V_real).^2))./length(V_real);
end
but I think it's just a waste of time because to me it seems it's redundant and makes the code less clear. Do you guys have any suggestions for a more intelligent solution?
Thank you very much!!
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Simulink 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!