Speed up the conversion of array of cells in numbers

I have a problem regarding the use of a for loop. I would like to avoid this loop in order to have a faster execution of my code.
I have a vector of cells called str_cell. The length of the vector is NUM_LINES = 300. Each cell contains a string of 11 numbers in a string format, which are delimited by a TAB.
In the for loop I convert the cells in vectors of numbers and I pass them in an array, called data, which has been previously initialized.
Here the code
for i = 1:NUM_LINES
numbers = str2double(strread(str_cell{i},'%s','delimiter','\t'));
data(i, :) = numbers(:);
end
When NUM_LINES is 300, my computer takes ~290ms to do that. I tried to avoid the for loop, but the command str2double works with a single string so that I had to pass cell by cell. Moreover I cannot change the way to get the files, in order to by-pass the problem. Do you have suggestions about avoiding this for loop?
Thanks in advance

2 Comments

How did you end up with this cell array? Did it come from a file? If it did, you could probably read it in as numbers.
Yes, it comes from a file, but it is super messy: • there is a header, • all the numbers have a comma instead of a point for the decimals • only the last 300 lines of numbers are important

Sign in to comment.

 Accepted Answer

Jan
Jan on 15 Feb 2013
Edited: Jan on 15 Feb 2013
S = sprintf('%s ', str_cell{:});
D = transpose(sscanf(S, '%g', [11, inf]));
Speed measurement:
str_cell = cell(1, 300);
for is = 1:300; str_cell{is} = sprintf('%d\t', 1:11); end
tic;
S = sprintf('%s ', str_cell{:});
D = transpose(sscanf(S, '%g', [11, inf]));
toc
% 0.004066 seconds (R2009a/64, Win7, Core2Duo)
% Original loop: 0.130204 seconds.
% Azzi's STR2NUM(CHAR): 0.027707 seconds.

More Answers (2)

Thank you guys for the suggestions! Both the scripts are very fast
Matlab R2009b win64
Intel i7 @ 2.66GHz Windows 7
1) My code -> Elapsed time is 0.375342 seconds.
2) Azzi's code -> Elapsed time is 0.070559 seconds.
3) Jan's code -> Elapsed time is 0.001708 seconds.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!