我想比较两个结构中的两个字符串。我的代码如下:
%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 是一个具有 1 个字段的 1x15 结构体
my_workspace 是具有 20 个字段的 1x1 结构
我只得到一个变量作为返回。 这段代码有什么问题?
最佳答案
我真的不明白你为什么要在这里创建一个新结构:variablesNames(t).Name
,因此我只是删除了该部分。
修改后的代码只是迭代variables
struct-array 并检查变量是否 my_workspace
有一个字段,其名称存储在 Name
中当前处理元素的字段,使用 isfield .
[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
关于Matlab:在for循环中比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38144205/