我有一个n by 2
矩阵,它包含指定字符串的子字符串的开始和结束索引。如何在没有for循环的情况下提取子字符串的n by 1
单元数组?
string = 'Hello World!';
ranges = [1 1;
2 3;
4 5;
3 7];
substrings = cell(size(ranges, 1), 1);
for i=1:size(ranges, 1)
substrings{i} = string(ranges(i, 1):ranges(i, 2));
end
预期结果:
substrings = 'H' 'el' 'lo' 'llo W'
您可以使用cellfun
使其成为单行操作:
str = 'Hello World!';
ranges = [ 1 1;
2 3;
4 5;
3 7];
% first convert "ranges" to a cell object
Cranges = mat2cell(ranges,ones(size(ranges,1),1),2);
% call "cellfun" on every row/entry of "Cranges"
cellfun(@(x)str(x(1):x(2)),Cranges, 'UniformOutput',false)
ans=
4×1单元阵列
{'H' } {'el' } {'lo' } {'llo W'}
我已将变量string
更改为str
,因为string
是MATLAB中的本机函数(将输入转换为字符串类型(。
虽然这是单线操作,但并不意味着它更高效:
Num = 1000000;
substrings = cell(size(ranges, 1), 1);
% time for-loop
tic
for j = 1:Num
for i = 1:size(ranges, 1)
substrings{i} = str(ranges(i, 1):ranges(i, 2));
end
end
toc;
Cranges = mat2cell(ranges,ones(size(ranges,1),1),2);
% time function-call
tic
for j = 1:Num
substrings = cellfun(@(x)str(x(1):x(2)),Cranges, 'UniformOutput',false);
end
toc;
Elapsed time is 3.929622 seconds. Elapsed time is 50.319609 seconds.