gpt4 book ai didi

matlab - 以编程方式打开 Simulink MATLAB 功能 block 的代码

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:17 26 4
gpt4 key购买 nike

我可以通过一些命令在 MATLAB 编辑器中打开本地 Simulink MATLAB 功能 block 的代码吗?

例如,假设我有一个名为 ma​​inModel.slx 的 Simulink 模型。

其中,有一个名为localFunction 的MATLAB 函数 block 。这未在 .m 文件中定义。

我将能够编辑路径为 mainModel/localFunction 的函数,而无需打开 simulink 窗口并双击函数 block 。这可能吗?

我当然已经尝试过open mainModel/localFunctionedit mainModel/localFunction。我可以访问其 StateFlow.EMChart 对象的句柄。


编辑:最小的(希望)完整且可验证的示例

我的最小 Simulink 模型如下图所示。代码位于其下方。为了可读性,我没有解决错误或故障。它不适合一般用途。

enter image description here

MATLAB 函数 block <​​em>localFunction 的函数代码是

function y = fcn(u)
y = 'findThis'; % I want to end up here, in the MATLAB editor!
end

我使用以下代码加载模型,搜索所有 MATLAB 功能 block 并找到包含字符串 'findThis' 的功能 block 。然后应找到名为 'localFunction' 的 MATLAB 函数 block 。再次,忽略错误。代码保存在名为 tmpScript.m 的脚本中。

% User set
model = 'mainModel';
expression = 'findThis';
blockType = 'Stateflow.EMChart'; % MATLAB function block, right?

% Load model
load_system(model)

% Find all MATLAB function block handles
blockHandles = find(slroot, '-isa', blockType);

% Find first block containing the defined expression
for iHandle = 1:numel(blockHandles)
tmpFind = strfind(blockHandles(iHandle).Script, expression);
if ~isempty(tmpFind)
break
end
end
foundBlockPath = blockHandles(iHandle ).Path; % Function block path
foundCharIdx = tmpFind; % Character index

% Print results in command window
fprintf('Function path: %s\n', foundBlockPath)
fprintf('Character index: %d\n', foundCharIdx)

在此示例中,路径应为 mainModel/localFunction 和字符索引 29(请注意函数第二行的三个前导空格,并且该行break '\n' 值一个字符)。命令窗口显示

>> tmpScript
Function path: mainModel/localFunction
Character index: 29
>>

因此,我可以加载模型并在其 MATLAB 函数 block 中搜索特定字符串。当我找到这个函数时,我希望能够在 matlab 编辑器中打开它。当我在 Simulink 窗口中双击模块时调用什么?

这些有效

open(foundBlockPath)
edit(foundBlockPath)
blockHandles(iHandle).openEditor

我无法更改 Simulink 模型本身。我不想更改函数脚本。我只想能够在 MATLAB 编辑器中打开它。

最佳答案

您可以使用以下方式在编辑器中打开代码,

view(blockHandles(iHandle))

关于matlab - 以编程方式打开 Simulink MATLAB 功能 block 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53279284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com