【问题标题】:Matlab function to pass a vector into simulink using 'fromworkspace'Matlab函数使用'fromworkspace'将向量传递到simulink
【发布时间】: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。

【问题讨论】:

    标签: matlab simulink


    【解决方案1】:

    这取决于您使用的版本。在最近的版本中,您可以指定要用作调用 sim 函数的一部分的工作区,例如:

    sim(modelName,'SrcWorkspace','current'); % the default is 'base'
    

    有关详细信息,请参阅documentation on sim。在旧版本中(不确定具体何时更改,我认为大约是 R0211a 或 R0211b),您必须使用 simset,例如:

     myoptions = simset('SrcWorkspace','current',...
                           'DstWorkspace','current',...
                           'ReturnWorkspaceOutputs', 'on');
     simOut = sim(mdlName, endTime, myoptions);
    

    更新

    要从 R2014b 中的 sim 返回数据,您需要在调用 sim 时使用输出参数,其中包含所有模拟输出,例如:

    simOut = sim(modelName,'SrcWorkspace','current'); % the default is 'base'
    

    simOut 是一个 Simulink.SimulationOutput 对象,包含时间向量、模型的记录状态和输出。

    【讨论】:

    • 我尝试了 R2014b 中的第一个选项,效果很好!除了它只将数据获取到 simulink 中,但会中断返回数据。 “SrcWorkspace”有效,但在“DstWorkspace”上抛出错误:'DstWorkspace' parameter is not supported in this form of syntax for sim command。返回变量有什么帮助吗?
    • 我通过写入 .mat 文件而不是使用 sprintf 改进了我的方法。这大大提高了性能,但我仍然想知道这样做的“正确”方法。
    • 查看我更新后的答案,但这一切都在sim 的文档中:uk.mathworks.com/help/simulink/slref/sim.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2017-02-19
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多