How can I get the first 10 characters of each cell in an array?
Mostrar comentarios más antiguos
I have a cell array (attached) containing dates that look like this:
'1999-01-02T18:24:37Z'
I'd like to get these dates into datenum format, which I can accomplish like this:
ct = char(t{2});
d = datenum(str2double(cellstr(ct(:,1:4))),str2double(cellstr(ct(:,6:7))),str2double(cellstr(ct(:,9:10))));
but that seems awfully convoluted and the str2double calls take a tremendous amount of time for long date lists. All I need are the year, month, and day in datenum format. Is there an elegant way to access only the first ten characters in the cell array t?
4 comentarios
jgg
el 9 de Dic. de 2015
Does C{n}(1:10) not work, where C is your cell array and n is an index which you loop over?
Chad Greene
el 9 de Dic. de 2015
Darn. I gave this another shot, but you might run into memory issues if you have millions of rows. The command A = cat(1,C{1:end}) will produce a char array with row size equal to the number of rows in your data and column length equal to the date size. Then, you can operate on this, so A(:,1:10) will return the first ten characters.
EDIT: I benchmarked it on my PC and this looks like it's quite fast relative to the other two methods:
- Method 1: (original) 0.35s
- Method 2: (loop) 32s
- Method 3: (cat) 0.007s
Hopefully this solves the problem!
EDIT2: I also think this probably won't work if the dates have different widths, so you might need to pad them out if they aren't in fixed size.
Chad Greene
el 10 de Dic. de 2015
Respuesta aceptada
Más respuestas (2)
paula
el 10 de Dic. de 2015
I believe this is what you want.
T = cell2mat(t);
T = cellstr(T(:,1:10));
d1 = datenum(T,'yyyy-mm-dd');
It's clean and fast. In terms of performance, you can compare it to your code that only converts one date, but you shouldn't.
1 comentario
Chad Greene
el 10 de Dic. de 2015
You can try FEX: DateStr2Num.mex . The format 31 should work: 'yyyy-mm-dd HH:MM:SS'. It is more than 100 times faster than Matlab's datenum functions.
1 comentario
Chad Greene
el 10 de Dic. de 2015
Categorías
Más información sobre Dates and Time en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!