首页 文章

Matlab函数使用'fromworkspace'将向量传递给simulink

提问于
浏览
1

我想编写一个包含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文件,其工作区块属性打开以保证完整性 .

Simulink model

(如果图像模糊,点击放大)

如果没有 mat2str()sprintf() ,有没有更简洁的方法呢? sprint 行需要永远运行,即使是大小为50k的向量也是如此 .

1 回答

  • 2

    这取决于您使用的是哪个版本 . 在最新版本中,您可以指定要用作 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);
    

    Update

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

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

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

相关问题