我想编写一个包含simulink块的matlab函数 . 该函数应将数据加载到simulink模型中,运行它,然后从函数返回数据 .
我能想到的唯一方法就是在simulink中使用'To Workspace'和'From Workspace'块 . 问题是'From Workspace'块不从功能范围中获取变量,只从工作空间范围中获取变量 .
下面是我能想到的唯一解决方案,它基本上将传入的向量转换为字符串,然后创建一个在模型启动时被调用的函数(实际上这与eval一样糟糕) .
这是代码:
function [ dataOut ] = run_simulink( dataIn )
% Convert data to a string (this is the part I would like to avoid)
variableInitString = sprintf('simin = %s;', mat2str(dataIn));
% we need both the name and the filename
modelName = 'programatic_simulink';
modelFileName = strcat(modelName,'.slx');
% load model (without displaying window)
load_system(modelFileName);
% Set the InitFcn to the god awful string
% this is how the dataIn actually gets into the model
set_param(modelName, 'InitFcn', variableInitString);
% run it
sim(modelName);
% explicity close without saving (0) because changing InitFcn
% counts as changing the model. Note that set_param also
% creates a .autosave file (which is deleted after close_system)
close_system(modelName, 0);
% return data from simOut that is created by simulink
dataOut = simout;
end
你运行它是这样的: run_simulink([0 0.25 0.5 0.75; 1 2 3 4]') 矩阵的第一部分是时间向量 .
最后,这是底层的simulink文件,其工作区块属性打开以保证完整性 .
(如果图像模糊,点击放大)
如果没有 mat2str() 和 sprintf() ,有没有更简洁的方法呢? sprint 行需要永远运行,即使是大小为50k的向量也是如此 .