您可以使用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 中的本机函数(将输入转换为string 类型)。
虽然这是单行操作,但不代表效率更高:
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.