【发布时间】:2015-04-28 09:40:30
【问题描述】:
我想编写一个环绕 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。
【问题讨论】: