一种方法是使用sprintf 将数组转换为一长串数字。然后,您可以将此字符串重塑为适当的形状。然后您可以使用cellstr 将重整后的字符串的每一行转换为单独的元胞数组元素。
out = cellstr(reshape(sprintf('%d', A), [], size(A,2)));
说明
先将矩阵转换成一长串数字。
s = sprintf('%d', A)
%// 1234123411112222111111112222222211111111
然后我们要对其进行重塑,使原始中的每一行数字都是输出中的一行数字
s = reshape(s, [], size(A,2))
%// 11121
%// 21121
%// 31121
%// 41121
%// 12121
%// 22121
%// 32121
%// 42121
然后我们可以使用cellstr 将每一行 this 转换成它自己的单元格数组
out = cellstr(s);
%// '11121'
%// '21121'
%// '31121'
%// '41121'
%// '12121'
%// '22121'
%// '32121'
%// '42121'
另一种方法
实现此目的的另一种方法是将A 的每一列视为一个位置值(即 10000 的位置、1000 的位置、100 的位置等)并将每一行转换为知道这一点的整数。这可以通过将每一行与10^(N-1:-1:0) 的数组相乘并对元素求和来轻松完成。这将为组合所有列的每一行产生一个数字。然后我们可以使用num2str 将其转换为字符串元胞数组。
%// Then convert each number to a string in a cell array
out = arrayfun(@num2str, A * (10.^(size(A, 2)-1:-1:0)).', 'uni', 0);
或者更短一点,我们可以从@rayryeng's 书中借一页并使用sprintfc 将此整数数组转换为字符串元胞数组:
out = sprintfc('%d', A * (10.^(size(A, 2)-1:-1:0)).');
基准测试
我很好奇这里和@rayryeng's answer 和Dev-iL's answer 中介绍的方法在增加行数时的性能。我写了一个快速测试脚本。
function tests()
% Test the number of rows between 100 and 10000
nRows = round(linspace(100, 10000, 100));
times1 = zeros(numel(nRows), 1);
times2 = zeros(numel(nRows), 1);
times3 = zeros(numel(nRows), 1);
times4 = zeros(numel(nRows), 1);
times5 = zeros(numel(nRows), 1);
%// Generate a random matrix of N x 5
getRandom = @(n)randi([0, 9], [n, 5]);
for k = 1:numel(nRows)
A = getRandom(nRows(k));
times1(k) = timeit(@()string_reshape_method(A));
A = getRandom(nRows(k));
times2(k) = timeit(@()base10_method(A));
A = getRandom(nRows(k));
times3(k) = timeit(@()sprintfc_method(A));
A = getRandom(nRows(k));
times4(k) = timeit(@()addition_method(A));
end
%// Plot the results
plot(nRows, cat(2, times1, times2, times3, times4)*1000);
legend({'String Reshape', 'Base-10 Conversion', 'sprintfc', 'addition of "0"'})
xlabel('Number of Rows in A')
ylabel('Execution Time (ms)');
end
function out = string_reshape_method(A)
out = cellstr(reshape(sprintf('%d', A), [], size(A,2)));
end
function out = base10_method(A)
out = sprintfc('%d', A * (10.^(size(A, 2)-1:-1:0)).');
end
function B = sprintfc_method(A)
B = sprintfc(repmat('%d', 1, size(A,2)), A);
end
function B = addition_method(A)
B = cellstr(char(A + '0'));
end
这是结果。