我想構建一個字符串數組:{'x_1', 'x_2', ..., 'x_n'}
。我知道什麼n
提前。用數值字符串快速填充單元陣列
for i = 1:n
myCell{i} = sprintf('x_%d', i);
end
有沒有更優雅的方式來做到這一點,即,一個班輪:我天真如下可能建立這個單元陣列?
我想構建一個字符串數組:{'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.
首先,我認爲一個你可以理解的明確的代碼,比如你所寫的代碼,要比單行代碼好得多。但如果你堅持...
arrayfun(@(x){sprintf('x_%d',x)},1:n)
另一種方式。你決定它是否更清晰。 ;)
strcat('x_',strtrim(cellstr(num2str((1:n)'))))
@yoda:感謝您編輯我的錯字。 – yuk 2011-12-20 22:46:26
我不認爲strtrim()
是必要的。所以稍微簡單:
strcat('x_',cellstr(num2str((1:n)')))
如果字符串必須是有效的MATLAB表達式,'strtrim'是必需的:'strcat('x _',cellstr(num2str([1; 1000])))'給出'x_ 1'和'x_1000'。注意1前面的空格。 – Kavka 2011-12-20 22:10:02
「一個班輪」不會比上面的代碼更優雅。如果效率是一個問題,由於for循環內單元數組的大小增加,可以在for循環之前添加'myCell = cell(1,n)'。請參閱[預分配數組](http://www.mathworks.com/help/techdoc/matlab_prog/f8-784135.html#f8-793781) – Kavka 2011-12-20 21:54:48