我想构建一个字符串的单元格数组:{'x_1', 'x_2', ..., 'x_n'}.我知道n提前是什么.我可能会按如下方式构建此单元格数组:
for i = 1:n
myCell{i} = sprintf('x_%d', i);
end
Run Code Online (Sandbox Code Playgroud)
是否有一种更优雅的方式来做到这一点,即单线?
您的代码比提供的一些答案快三倍:
%
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.
Run Code Online (Sandbox Code Playgroud)