Change Simulink parameters in Matlab function

3 次查看(过去 30 天)
I have a Simulink model (SM) and want to write a Matlab function (MF) (to which I pass some parameters of SM), in which I would like to change some parameters of SM and simulate it. I know how to change SM's parameters from workspace using set_param and Simulink.Parameter but I fail to make it work inside MF. As an example, suppose you have created SM and inside there is a Gain-Block called Gbl. I would like to use MF to update/change the value of Gbl. Calling MF with the variables var1 and var2 (see the code below) doesn't work (either var1 and var2 are in workspace, then MF will not update them or if they are not, there will be an error saying that var1 doesn't exist)
function MF(var1,var2)
set_param('SM/Gbl','Gain','2*var1*var2') % this doesn't work as intended inside a function
simOut = sim('SM','SaveOutput','on','OutputSaveName','yout','SaveFormat','Dataset');
yout = simOut.get('yout');
How can you make it work, so var1 and var2 get updated to the values passed to MF?
Further considerations: I would like to use MF for some optimization, so the changing of the parameters of SM should be very fast. Any ideas how to do that?
  1 个评论
Kilian Lasch
Kilian Lasch 2022-1-14
编辑:Kilian Lasch 2022-1-14
Have you found a solution or workaround for the problem? I'm currently facing the same error.

请先登录,再进行评论。

回答(1 个)

Peter O
Peter O 2020-8-29
Simulink will look for variables in MATLAB's base workspace by default. Since var1 and var2 are defined in the function's workspace, it won't find them and you'll get that error. To have it use the workspace of a function, you need to pass an additional argument to the sim function.
Try:
sim('SM','SaveOutput','on','OutputSaveName','yout','SaveFormat','Dataset','SrcWorkspace','current')
There's a couple restrictions if you're running in parfor loops or using the Accelerator mode, but there are workarounds if those conditions apply.

类别

Help CenterFile Exchange 中查找有关 Model, Block, and Port Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by