【问题标题】:Matlab: Compare strings in a for loopMatlab:在for循环中比较字符串
【发布时间】:2016-07-01 11:23:39
【问题描述】:

我想比较来自两个结构的两个字符串。我的代码如下:

%matlab模型扫描

[variables] = Simulink.findVars('myModell');
variablesNames =[];

%save the names of all the variables in variablesNames
for t= 1:length(variables)
     variablesNames(t).Name = variables(t).Name;   
end

%scan workspace
for f = fieldnames(my_workspace)
    found = false;
    for c = 1:length(variablesNames)
        if strcmp(f{c}, variablesNames(c))        
            found = true;
            result = 'Found in Workspace: ';
        end    
        if ~found
            result = 'Not found inside Workspace';
        end
    end
    disp(['Workspace Variable: ', sprintf('%-*s',40,f{c}), result]);
end

variablesNames 是一个 1x15 结构,有 1 个字段

my_workspace 是具有 20 个字段的 1x1 结构

我只有一个变量作为回报。 这段代码有什么问题?

【问题讨论】:

  • f = fieldnames(my_workspace) ?你的意思是f = 1:numel(fieldnames(my_workspace))?
  • 您的意思是result 中只有一个值?这很正常,因为您每次循环时都会覆盖它。尝试将result 更改为result{c}
  • @Ander Biguri :我尝试了您的建议,但请考虑 f 是 20x1 单元格。这是失败:来自非单元格数组对象的单元格内容引用。如果 strcmp(f{c}, variablesNames(c)),stackoverflow 中的错误(第 13 行)
  • @BillBokeey:我也试过了。但结果仅包含 variablesNames 中的一个变量(编号 5)

标签: matlab for-loop simulink string-comparison


【解决方案1】:

我真的不明白你为什么要在这里创建一个新结构:variablesNames(t).Name,因此我只是删除了那部分。

修改后的代码只是遍历variables struct-array 并使用isfield 检查变量my_workspace 是否具有存储在当前处理元素的Name 字段中的值的名称的字段。

[variables] = Simulink.findVars('myModell');

for i = 1:length(variables)
   if isfield(my_workspace, variables(t).Name)
      result = 'Found in Workspace: ';
   else
       result = 'Not found inside Workspace';
   end

   disp(['Workspace Variable: ', sprintf('%-*s', 40, variables(t).Name), result]);
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多