从字符串的元胞数组中读取特定字符
Read specific character from cell-array of string
我有一个维度为 1x6
的元胞数组,如下所示:
A = {'25_2.mat','25_3.mat','25_4.mat','25_5.mat','25_6.mat','25_7.mat'};
我想从 A{1}
中读取 '_'
之后的数字,即 2
我的示例
使用cellfun
, strfind
and str2double
out = cellfun(@(x) str2double(x(strfind(x,'_')+1:strfind(x,'.')-1)),A)
它是如何工作的?
This code simply finds the index of character one number after the occurrence of '_'
. Lets call it as start_index
. Then finds the character one number lesser than the index of occurrence of '.'
character. Lets call it as end_index
. Then retrieves all the characters between start_index
and end_index
. Finally converts those characters to numbers using str2double
.
示例输入:
A = {'2545_23.mat','2_3.mat','250_4.mat','25_51.mat','25_6.mat','25_7.mat'};
输出:
>> out
out =
23 3 4 51 6 7
您可以使用大括号访问单元格的内容{...}
。一旦可以访问内容,就可以使用索引来访问字符串的元素,就像访问普通数组一样。例如:
test = {'25_2.mat', '25_3.mat', '25_4.mat', '25_5.mat', '25_6.mat', '25_7.mat'}
character = test{1}(4);
如果你的字符串长度是可变的,你可以使用strfind
来找到你想要的字符的索引。
假设数字是在_
符号后的非负整数:使用正则表达式与lookbehind,然后从字符串转换为数字:
numbers = cellfun(@(x) str2num(x{1}), regexp(A, '(?<=\_)\d+', 'match'));
我有一个维度为 1x6
的元胞数组,如下所示:
A = {'25_2.mat','25_3.mat','25_4.mat','25_5.mat','25_6.mat','25_7.mat'};
我想从 A{1}
中读取 '_'
之后的数字,即 2
我的示例
使用cellfun
, strfind
and str2double
out = cellfun(@(x) str2double(x(strfind(x,'_')+1:strfind(x,'.')-1)),A)
它是如何工作的?
This code simply finds the index of character one number after the occurrence of
'_'
. Lets call it asstart_index
. Then finds the character one number lesser than the index of occurrence of'.'
character. Lets call it asend_index
. Then retrieves all the characters betweenstart_index
andend_index
. Finally converts those characters to numbers usingstr2double
.
示例输入:
A = {'2545_23.mat','2_3.mat','250_4.mat','25_51.mat','25_6.mat','25_7.mat'};
输出:
>> out
out =
23 3 4 51 6 7
您可以使用大括号访问单元格的内容{...}
。一旦可以访问内容,就可以使用索引来访问字符串的元素,就像访问普通数组一样。例如:
test = {'25_2.mat', '25_3.mat', '25_4.mat', '25_5.mat', '25_6.mat', '25_7.mat'}
character = test{1}(4);
如果你的字符串长度是可变的,你可以使用strfind
来找到你想要的字符的索引。
假设数字是在_
符号后的非负整数:使用正则表达式与lookbehind,然后从字符串转换为数字:
numbers = cellfun(@(x) str2num(x{1}), regexp(A, '(?<=\_)\d+', 'match'));