【问题标题】:How to extract substrings with different lengths?如何提取不同长度的子串?
【发布时间】:2021-02-20 05:37:34
【问题描述】:

我有一个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'

【问题讨论】:

标签: string matlab cell-array


【解决方案1】:

您可以使用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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多