给定矩阵: - 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
我希望以更简单的方式做到这一点而没有循环。
答案 0 :(得分:5)
使用num2str
和strsplit
的另一种方法:
A1 = strsplit(num2str(A))
答案 1 :(得分:3)
您可以将arrayfun与anonymous function结合使用:
B = arrayfun(@(x) {num2str(x)}, A);
cellfun有点快,也很好用:
B = cellfun(@num2str, num2cell(A), 'uni', 0);
最快的解决方案是此solution的改进版本(归功于obchardon)
B = regexp(num2str(A), '\s+', 'split');
答案 2 :(得分:0)
以下解决方案大致从最快到最慢排序。请注意解决方案如何分为三个数量级的性能等级。
这是在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.
Takeaways:优先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