sprintf: how to efficiently create a string of 75 numbers, separated by comma
13 次查看（过去 30 天）
I have an array which contains 75 numeric elements. I want to write these numbers as a string separated by a comma. If there were few numbers, I could use 'sprintf' as follows:
I need an efficient way to do it when there are many entries in A.
Star Strider 2018-4-27
You can still use sprintf. You just need to create a ‘dynamic’ format string:
A = 1:5;
str = sprintf([repmat('%d,',1, numel(A)-1), '%d'], A)
That will adapt for any ‘A’ vector.
"I need an efficient way to do it when there are many entries in A."
This is probably about the most efficient way:
A = 1:5;
str = sprintf(',%d',A);
str = str(2:end);
Timing comparisons for 1e4 iterations:
Elapsed time is 0.539053 seconds. % this answer.
Elapsed time is 2.54425 seconds. % Star Strider's answer.