【问题标题】:Is it possible to make a while error or while no error Matlab是否有可能出现一段时间错误或没有错误Matlab
【发布时间】:2019-04-16 09:27:37
【问题描述】:

在我的 matlab 脚本中,我正在解析具有特定标签结构的文本文件,并为我发现的每个特殊标签的出现创建 Simulink 块。我有一个简单的例子:

[Link]
  Link_Name : On/Off 
  Link_ID : _sZfSkku9Eemg_bhrv2HEbw

[Link] 
  Link_Name : On/Off
  Link_ID : _qsYbsVeeEemna8dVWPKMTw

您可以看到这不是同一个对象,但它们具有相同的名称,因此当我在 matlab 中为每个链接创建一个 simulink 块时,我发现我有一个错误 "can't create a new On/Off Block" 类似的东西。

所以我将 ID 放在块的描述中,如果相同,我只需更新名称,以防用户更改文本文件中的名称: set_param(gcb,'Name', link_NameValue);

如果不同,我创建一个新块:

add_block('simulink/Ports & Subsystems/In1',[component_NameValue '/' link_NameValue], 'MakeNameUnique', 'on');

问题在于'MakeNameUnique', 'on' 如果我多次运行我的脚本并且set_param 我有一个错误,它将创建一个无限的块 The name 'On_Off' already exists

所以我想做一个这样的while循环:

while error "can't create a new block"  
    add a "x" at the end of the name of the new block
end
or
while error "The name 'On_Off' already exists"
    add a "x" at the end of the name of the existing block 
end

因此,即使我有 4 个名称为 On/Off 的 [Link],它也会创建 On/Off、On/Offx、On/Offxx、On/Offxxx 或在可能的情况下以数字结尾。

感谢您的帮助!我试图尽可能简短地解释。

【问题讨论】:

    标签: matlab while-loop try-catch


    【解决方案1】:

    您应该使用try, catch 方法进行一些测试。由于您没有给我们 MCVE,所以我只能给您未经测试的代码:

    i=0
    While i==0
        i=1 %An assumption that code will pass
        try
            sim('ModelName', ParamStruct);
        catch SimErr
            i=0
            %change some parameters in your model below
            %add a "x" at the end of the name of the new block or whatever you need
        end
    end
    

    所以基本上 - 如果没有错误,i 将保持更改为 1 并停止循环。如果发生错误 - 它也会将i 改回 0,以保持循环继续进行。在 catch 语句中,您可以将一些更改传递给您的模型,以迭代地尝试使用新参数,只要它不会通过。

    【讨论】:

    • 谢谢!我是这样尝试的:trying = true;n = 1;`while try``try``set_param(gcb,'Name',nameParam);`trying = false;`catch`nameParam = strcat(nameParam, n);`end``end` 这是一样的我的想法。
    • 是的,看起来概念是一样的。只要它对您有用,就完全没问题。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多