String 单元格数组中字符串部分的Matlab引用
我正在寻找一种引用存储在单元格数组中的字符串部分的方法。我需要这样做,以便生成一个逻辑语句,将我要查找的字符串与单元格数组中的字符串部分相匹配 假设我的单元格数组如下所示:String 单元格数组中字符串部分的Matlab引用,string,matlab,cell,String,Matlab,Cell,我正在寻找一种引用存储在单元格数组中的字符串部分的方法。我需要这样做,以便生成一个逻辑语句,将我要查找的字符串与单元格数组中的字符串部分相匹配 假设我的单元格数组如下所示: cellname = { 'B_1J_1234_1236' , 'A_1W_2345_2349' , 'C_2J_9876_9879' , 'B_1W_5432_5438'} 我希望在单元格数组中找到满足以下条件的字符串: 'B'作为字符串的第一部分 '1W'作为字符串的第二部分 第一个数字(第三部分)小于5434 第二个
cellname = { 'B_1J_1234_1236' , 'A_1W_2345_2349' , 'C_2J_9876_9879' , 'B_1W_5432_5438'}
我希望在单元格数组中找到满足以下条件的字符串:
'B'
作为字符串的第一部分'1W'
作为字符串的第二部分find(strncmp(cellname,'B_1W',4))
但我找不到一种方法来包括后一种条件。有什么想法吗
编辑:
理想情况下,我想我会想办法:
find(strncmp(cellname,'B_1W',4) & cellname{ "any element" } (6:9) < 5434 & cellname{ "any element" } (11:14) > 5436)
find(strncmp(cellname,'B_1W',4)&cellname{“任何元素”}(6:9)<5434&cellname{“任何元素”}(11:14)>5436)
但我不知道如何引用“任意元素”的一部分。您可以使用
cellfun
和自定义函数来解决此问题。在此函数中,您可以使用带分隔符的strsplit
将字符串拆分为子字符串。然后只需检查是否满足相应返回true
或false
的所有条件。请注意,我们需要将第三个和第四个字段中的字符串转换为数字。这可以通过str2double
完成
function main
cellname = { 'B_1J_1234_1236' , ...
'A_1W_2345_2349' , ...
'C_2J_9876_9879' , ...
'B_1W_5432_5438' };
R = cellfun(@check, cellname, 'UniformOutput',1)
find(R==true)
end
function out = check(in)
S = strsplit(in,'_');
out = strcmp(S{1},'B') && strcmp(S{2},'1W') && ...
str2double(S{3})<5434 && str2double(S{4})>5436
end
如果您想使用类似于您提议的内容,您也可以使用
cellfun
:
find(strncmp(cellname,'B_1W',4) & ...
cellfun(@(x)str2double(x(6:9))<5434,cellname) & ...
cellfun(@(x)str2double(x(11:14))>5436,cellname))
find(strncmp(cellname,'B_1W',4)&。。。
cellfun(@(x)str2double(x(6:9))5436,手机名))
与Matt的非常相似,但只有一行
cellfun(@(x) strcmp(x{1}, 'B') && strcmp(x{2}, '1W') && (str2num(x{3}) < 5434) && (str2num(x{4}) > 5436), cellfun(@(x) strsplit(x, '_'), cellname(:)', 'uni', 0))
cellfun(@(x)strcmp(x{1},'B')&&strcmp(x{2},'1W')&&(str2num(x{3}<5434)&(str2num(x{4}>5436),cellfun(@(x)strsplit(x,'uu'),cellname(:),'uni',0))
使用正则表达式:
cellfun(@(x) ~isempty(x) && str2num(x.m)<5434 && str2num(x.n)>5436, ...
regexp(cellname, '^B_1W_(?<m>\d+)_(?<n>\d+)', 'names'))
cellfun(@(x)~isempty(x)和&str2num(x.m)5436。。。
regexp(cellname,^B\u 1W\u(?\ d+)\u(?\ d+),'names'))
cellfun(@(x) ~isempty(x) && str2num(x.m)<5434 && str2num(x.n)>5436, ...
regexp(cellname, '^B_1W_(?<m>\d+)_(?<n>\d+)', 'names'))