【问题标题】:Converting a numeric array into a string cell array将数值数组转换为字符串元胞数组
【发布时间】:2016-07-04 11:23:21
【问题描述】:

给定矩阵:- A = [0 1 2 3 4 5];

我想将它转换成这样的字符串元胞数组:A = {'0' '1' '2' '3' '4' '5'};

我可以使用:

A = [0 1 2 3 4 5];

for i=1:6
    A1{i}= num2str(A(i));
end
A1

我想用一种更简单的方式来做这件事,并且没有循环。

【问题讨论】:

    标签: arrays string matlab


    【解决方案1】:

    num2strstrsplit 的另一种单行方法:

    A1 = strsplit(num2str(A))
    

    【讨论】:

    • +1 不错且快速的解决方案,但出于兼容性和速度的原因,我建议使用 regexp A1 = regexp(num2str(A), '\s+', 'split'); 在我的测试中,regexpstrsplit 快七倍
    【解决方案2】:

    您可以将arrayfunanonymous function 结合使用:

    B = arrayfun(@(x) {num2str(x)}, A);
    

    cellfun 稍微快一点,也可以正常工作:

    B = cellfun(@num2str, num2cell(A), 'uni', 0);
    

    最快的解决方案是这个solution 的改进版本(感谢obchardon

    B = regexp(num2str(A), '\s+', 'split');
    

    【讨论】:

    • arrayfun 只是循环的一个包装器,所以它与 OP 基本相同。
    • @Dan 不完全是。这实际上会给每个单元格一个数字,并且 OP 将在每个单元格中创建一个带有一个字符的字符串。我实际上认为这更接近问题所在,因为这是产生等效代码的唯一答案。
    • @Patrik 我看不出这和 OP 循环之间有什么区别,即使是多位数字......
    • 我同意@Dan 对我来说没有“计算”差异,这种方法仍然很慢。
    【解决方案3】:

    以下解决方案大致按从最快到最慢的顺序排列。请注意解决方案如何分为三个数量级的性能等级。

    这是在 iMac 上使用来自 MacPorts 的预编译 Octave 4.2.2; octave @4.2.2_1+accelerate+app+docs+fltk+gfortran+graphicsmagick+qt5+sound.

    Elapsed time is 0.00452113 seconds.
    Elapsed time is 0.0121579 seconds.
    Elapsed time is 0.0185781 seconds.
    Elapsed time is 0.0243361 seconds.
    Elapsed time is 0.025944 seconds.
    Elapsed time is 2.42572 seconds.
    Elapsed time is 2.4809 seconds.
    Elapsed time is 2.48733 seconds.
    Elapsed time is 2.49299 seconds.
    

    要点:sprintf 优于任何其他字符串转换,ostrsplit 优于 strsplit

    clear all
    A=rand(1,2000);
    #A=1:2000;
    
    tic
    A4=ostrsplit(sprintf("%g ",A), " ", true);
    toc;tic
    
    A9=ostrsplit(num2str(A), " ", true);
    toc;tic
    
    A8=regexp(num2str(A), '\s+', 'split');
    toc;tic
    
    A3S=num2str(A');
    A3=mat2cell(A3S,ones(1,size(A3S,1)))';
    A3=strtrim(A3);
    toc;tic
    
    A5=strsplit(num2str(A));
    toc;tic
    
    A7=cellfun(@num2str, num2cell(A), 'uni', 0);
    toc;tic
    
    A6=arrayfun(@(x) {num2str(x)}, A);
    toc;tic
    
    A2=cell(size(A));
    for i = 1:numel(A)
      A2{i} = num2str(A(i));
    endfor
    toc;tic
    
    for i = 1:numel(A)
      A1{i} = num2str(A(i));
    endfor
    toc;tic
    

    【讨论】:

    • 该问题未标记 Octave。所以一些解决方案是无关紧要的,其他的已经发布了。其中只有一个是新的。最好承认您已包含在您的解决方案中的已发布解决方案。 ' 不是转置。
    猜你喜欢
    • 2015-03-15
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多