Matlab:比较for循环中的字符串
Matlab: Compare strings in a for loop
我想比较来自两个结构的两个字符串。我的代码如下:
%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 结构
我只有一个变量return。
这段代码有什么问题?
我真的不明白你为什么要在这里创建一个新结构:variablesNames(t).Name
,所以我只是删除了那部分。
修改后的代码只是遍历 variables
结构数组并检查变量 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模型扫描
[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 结构
我只有一个变量return。 这段代码有什么问题?
我真的不明白你为什么要在这里创建一个新结构:variablesNames(t).Name
,所以我只是删除了那部分。
修改后的代码只是遍历 variables
结构数组并检查变量 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