在matlab中如何判断数组是否包含某个元素?

问题描述

在matlab中,我们有时需要对字符串数组进行分类、筛选等,我们可以通过以下代码实现。

代码复现

例题一

要判断一个 cell 数组中是否包含特定的单词(字符串),你可以使用循环遍历每个 cell 元素,并使用字符串处理函数来判断每个单元格中是否包含该单词。以下是一个示例:

% 创建一个包含字符串的 cell 数组
cellArray = {'This is a sample string.', 'Another cell.', 'No c here.', 'Contains c.'};
wordToFind = 'c';

% 初始化一个标志变量
found = false;

% 遍历每个 cell 元素
for i = 1:numel(cellArray)
    if contains(cellArray{i}, wordToFind)
        found = true;
        break;  % 一旦找到,就可以退出循环
    end
end

if found
    disp('The word c is present in the cell array.');
else
    disp('The word c is not present in the cell array.');
end

例题二

在这里插入图片描述
我们将FileNames进行分类,区分出包含c和d字符串数组。
FileNames如图所示。

n = length(FileNames);
cc=0;
dd=0;
FileNamesc={};
FileNamesb={};

for ii=1:n
tem1=  FileNames(ii);
wordToFind = 'c';
found = false;
for i = 1:numel(tem1)
    if contains(tem1{i}, wordToFind)
        found = true;
        break;  
    end
end

if found
    cc=cc+1;
    FileNamesc(cc,1)=FileNames(ii);
else
    dd=dd+1;
     FileNamesb(dd,1)=FileNames(ii);
end
end

注释:
1.定义cell数组FileNamesc={},数值数组定义为格式为:FileNamesc=[]。
2.tem1= FileNames(ii);取第 i i ii ii个元素进行判断。
3.wordToFind = ‘c’;为区分的元素。
4.FileNamesc(cc,1)=FileNames(ii);cell数组和cell数组之间转化用(),cell转化为double用{}。
eg:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值