more efficient way to use strtok / selecting parts of a string
iliya ka asked
on 28 Jan 2012 at 11:52
Accepted Answer from Daniel
Greetings, I have a huge cell array with time data arranged in the following format : [one empty cell]; ABC/DEF QTR/3/99 (Thousands); ABC/DEF QTR/6/99 (Thousands); ABC/DEF QTR/9/99 (Thousands); ABC/DEF QTR/12/99 (Thousands); etc... I would like to change the format into this : ABC/DEF; QTR/3/99; QTR/6/99; QTR/9/99; QTR/12/99; etc... I've solved the problem but think it can be done much more efficiently: [varname, mthtime2(2:end)] = strtok(mthtime2(2:end)); mthtime2(2:end)= strtok(mthtime2(2:end));% drops the "thousands" mthtime2(1)=varname(1); Suggestions for a faster method would be most appreciated. Thank you for your time! Iliya Products |
|---|
If the format is as rigid as your example ...
Given a cell array
x = {[]; 'ABC/DEF QTR/3/99 (Thousands)'; 'ABC/DEF QTR/6/99 (Thousands)'; 'ABC/DEF QTR/9/99 (Thousands)'; 'ABC/DEF QTR/12/99 (Thousands)'};
Then for each element
y = x{i};
you want
y(9:17);
and then need to deal with the possible blank space. The function deblank can handle this. Putting it all together ...
x = {[]; 'ABC/DEF QTR/3/99 (Thousands)'; 'ABC/DEF QTR/6/99 (Thousands)'; 'ABC/DEF QTR/9/99 (Thousands)'; 'ABC/DEF QTR/12/99 (Thousands)'};
[{'ABC/DEF'};cellfun(@(y)(deblank(y(9:17))), x(2:end), 'UniformOutput', false)]
edit to handle variable ABC/DEF
firstCell = x{2};
[{firstCell(1:7)};cellfun(@(y)(deblank(y(9:17))), x(2:end), 'UniformOutput', false)]
Thank you very much daniel! It's close to being ok, but the 'ABC/DEF' changes from on variable to another (but kept in the same format) therefore it has to be read from the file.
any more suggestions ?
Iliya
This should be a comment on my answer and not a new answer. It makes following threads easier. See my edit to my answer.
Contact us at files@mathworks.com
2 comments
Is the mthtime2(1)=varname(1) commented out, or should it be on the next line?
In order to get what iilya wants, mthtime2(1)=varname(1) needs to be uncommented.