给定矩阵: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
我希望以更简单、不需要循环的方式完成此操作。
使用 num2str
和 strsplit
的另一种单行方法:
A1 = strsplit(num2str(A))
arrayfun
只是一个循环的包装器,所以基本上和OP完全一样。 - Danoctave @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
而不是其他任何to-string转换,以及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
'
不是转置。 - Sardar Usama
regexp
A1 = regexp(num2str(A), '\s+', 'split');
在我的测试中,regexp
比strsplit
快七倍。 - serial