0

I have a cell in Matlab that looks like this:

'1406200719565'
'1406200719583'
'1406200719598'
'1406200730211'
'1406200730226'
'1406200730242'
'1406200731023'
'1406200731889'
'1406200732801'
'1406200733670'

I want no to convert each of this String into a double and then into a double array. I followed various approaches I could find in the net, but none of them worked. E.g. I used the approach recommended here, but the result is just a vector with NaNs. What else can I do?

Community
  • 1
  • 1
user6189
  • 653
  • 1
  • 7
  • 15

2 Answers2

5

Have you tried this:

S={'1406200719565'
   '1406200719583'
   '1406200719598'
   '1406200730211'
   '1406200730226'
   '1406200730242'
   '1406200731023'
   '1406200731889'
   '1406200732801'
   '1406200733670'}

cellfun(@str2num, S)
Dan
  • 45,079
  • 17
  • 88
  • 157
1

It appears there is no reason to use cellfun. str2double is already vectorized and works with cells. However, when comparing performance cellfun is actually significantly (i.e. measurable) faster!

S={'1406200719565'
   '1406200719583'
   '1406200719598'
   '1406200730211'
   '1406200730226'
   '1406200730242'
   '1406200731023'
   '1406200731889'
   '1406200732801'
   '1406200733670'}

X = zeros(10,1);

tic
for ii = 1:20000
X=str2double(S);
end
toc

Output: Elapsed time is 3.908324 seconds.

tic
for ii = 1:20000
X = cellfun(@str2double, S);
end
toc

Output: Elapsed time is 3.357150 seconds.

As suggested by @Divakar a comparison using a larger cell array emphasizing the gain in performance by using cullfun:

S=cellstr(num2str(randi(150000,10000,1)));
X = zeros(150000,10000);
tic
X=str2double(S);
toc
tic
X = cellfun(@str2double, S);
toc

Resulting in:

Direct: Elapsed time is 0.778316 seconds.

Using cellfun: Elapsed time is 0.173727 seconds.

Note Virtually no difference in using str2num or str2double. str2num seems 3% slower, but is not significantly.

EJG89
  • 1,189
  • 7
  • 17
  • 1
    I think a fair comparison would be when you increase the datasize, something like - `S = cellstr(num2str(randi(1000000,100000,1)))`. – Divakar Jul 25 '14 at 09:51
  • Cellfun shows a significant increase in performance – EJG89 Jul 25 '14 at 10:33
  • +1 for the comparisons, but can you add my solution into your time test please? i.e. `str2num` instead of `str2double`? – Dan Jul 25 '14 at 10:42