关于在我的MATLAB代码中使用contains()输出If语句的困惑



如果有人提出类似问题,我们深表歉意。

我试图比较两个公司名称列表,并在for循环中创建了一系列if语句,在if语句中创建了contains()函数。

逻辑是,对于原始列表中的每个公司名称X,将计算if语句:

  1. if:如果在两个列表的前50名中都有匹配项,那么我会得到带有语句"的公司名称;X在2020年前50名名单中
  2. CCD_ 7:如果在原始列表的前50名和第二列表的其余部分中存在匹配;X在2020年的总名单中
  3. else:如果没有匹配,我得到与声明"不匹配的公司名称;X不在2020年的名单中

到目前为止,我的输出是所有与(3(中的语句匹配的公司,即我的else语句。不知道为什么,但我的else语句正在捕获我的ifelseif语句输出。

代码:

year1 = data(1:end, 1:4); %tables
year30 = data(1:end, 121:124);
names30_50 = year30{1:50, 2}; %cells
names30_all = year30{:, 2};
names1_50 = year1{1:50, 2};
names1_all = year1{:, 2};

for i = 1:height(names1_50)
if contains(names30_50, names1_50{i})  %comparing both top 50 lists
disp(names1_50{i})
fprintf('%s is in the 2020 top 50 list.n',names1_50{i})
elseif contains(names30_all, names1_50{i})  %comparing top 50 of 1990 with all of 2020
disp(names1_50{i})
fprintf('%s is in the 2020 overall list.n',names1_50{i})
else
fprintf('%s is not in the 2020 list.n',names1_50{i});
end
end

输出示例:

General Motors is not in the 2020 list.
Ford Motor is not in the 2020 list.
Exxon Mobil is not in the 2020 list.
Intl. Business Machines is not in the 2020 list.
General Electric is not in the 2020 list.
Mobil is not in the 2020 list.
Altria Group is not in the 2020 list.
Chrysler is not in the 2020 list.

它还在继续,但所有这些公司都在这两个名单中。

contains((函数用于评估字符串或字符中是否存在模式。实例你有一个字符ch='my_car';
%You have a char
ch = 'my_char';
%and another piece of char, the pattern
pattern = 'char';
%Evaluate if pattern is in my_char
disp(contains(ch, pattern))
% It returns true

(对不起,我不知道如何包含matlab代码(

如果我做对了,你的第一个论点就是一个单元格。在这种情况下,contains函数返回一个逻辑数组。对于单元格names30_50的每个元素,您都知道它是否包含names1_50{i}char。

但是,如果给if语句一个逻辑数组,那么只有当数组中的ALL元素为true时,它才会执行块。在你的情况下,这显然永远不会发生。

你需要做的是写

if any(contains(names30_50, names1_50{i}))
...

如果逻辑数组中至少有一个元素为true,则any((函数返回true。

顺便说一句,我宁愿使用strcmp((函数而不是contains((。

我希望我能正确理解你的问题。

最新更新