我想构建一个字符串元胞数组:{'x_1', 'x_2', ..., 'x_n'}
。我提前知道 n
是什么。天真地,我可能会按如下方式构建此元胞数组:
for i = 1:n
myCell{i} = sprintf('x_%d', i);
end
是否有更优雅的方式来做到这一点,即单行代码?
最佳答案
您的代码比提供的一些答案快三倍:
%
n = 1000;
tic
myCell = cell(1,n);
for i = 1:n
myCell{i} = sprintf('x_%d', i);
end
toc
tic
aCell = arrayfun(@(x){sprintf('x_%d',x)},1:n);
toc
tic
bCell = strcat('x_',cellstr(num2str((1:n)')));
toc
tic
cCell = strcat('x_',strtrim(cellstr(num2str((1:n)'))));
toc
>> Elapsed time is 0.011541 seconds.
>> Elapsed time is 0.030992 seconds.
>> Elapsed time is 0.027931 seconds.
>> Elapsed time is 0.030453 seconds.
关于matlab - 用数字字符串快速填充元胞数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8581419/