I am trying to convert an array of numbers to a single string of the numbers separated by 1s. For example:
10
5
7
would become '10 1 5 1 7 1'.
In order to do this I am using the following function:
function [string] = ArrayToString(Array)
string = cell(1,11);
for j = 1:size(Array,2)
str = ['Column', num2str(j) , ' '];
for i = 1:size(Array,1)
str = [str, num2str(Array(i,j)), ' 1 '];
end
string (1,j) = cellstr(str);
end
end
This is incredibly slow due to num2str (according to the profiler). Is there any alternative I can use to create this string on the fly. Also, is there a way to pre-allocated space for the string, perhaps that is part of the issue.
Any help is greatly appreciated.
Thanks.
A = [10;5;7];
str = sprintf('%.0f 1 ',A);
str(end) = [];
--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.
> 10
> 5
> 7
> would become '10 1 5 1 7 1'.
>> Array = round(12345 * rand(100,50));
>> tic;B = num2str(Array(:) .', '%d 1 '); toc
Elapsed time is 0.006273 seconds.
>> B(1:50)
ans =
689 1 3194 1 5431 1 3510 1 8379 1 11723 1 9554 1 7
>> tic;B = num2str(reshape([Array(:),ones(numel(Array),1)],1,[]));toc
Elapsed time is 0.029967 seconds.
>> tic;B = sprintf('%d 1 ', Array);toc
Elapsed time is 0.005332 seconds.
>> tic;B = ArrayToString(Array);toc
Elapsed time is 0.338314 seconds.
Examining these timings, we can see that it isn't num2str() itself that is the
problem: the first code variant using num2str gives the second fastest timing
and even the much more complex version with twice as many numbers to convert
is still 10 times faster than your routine.
--
.signature note: I am now avoiding replying to unclear or ambiguous postings.
Please review questions before posting them. Be specific. Use examples of what you mean,
of what you don't mean. Specify boundary conditions, and data classes and value
relationships -- what if we scrambled your data or used -Inf, NaN, or complex(rand,rand)?