Consolidate Substring Code using Cellfun
4 views (last 30 days)
Show older comments
I have read data from an excel sheet. The data Iam trying to manipulate is in the second column. First line is the header. i would like to extract last 4 characters of each content.
D = dta_txt(2:end,2);
lastFourChar = cell(length(D),1);
chArr = char(D);
for i = 2:length(D)
oneString = chArr(i,:);
trimmedString = strtrim(oneString);
lastFourChar(i) = cellstr( trimmedString( length(trimmedString)-3 : length(trimmedString) ));
% check if last 4 characters contain '/' and extract those data alone from dta_txt
end
I request help to the improve the above code using cellfun and anonymous function. Also I would like to know how to check for presence of '/' and extract appropriate data from the cell array dta_txt if the check returns 1.
Thank You !
0 Comments
Accepted Answer
Laura Proctor
on 23 Dec 2012
It isn't necessary to loop through the char array. You could do something like this:
y = { '10/5/05' ; '18/2/2004' ; '3/3/2003' }
lastFour = cellfun(@(x)x(end-3:end),y)
You can create a logical array with this information.
k = cellfun(@(x) ~isempty(x),strfind(lastFour,'/'))
years = zeros(length(y),1)
years(~k) = str2double(lastFour(~k))
years(k) = 2000 + str2double(lastFour{k}(3:4))
I think you might find it worthwhile to go back to some of your old posts and see some of the solutions given. This is a solution to the specific question you asked, but there is a better solution to your general problem.
1 Comment
Jan
on 24 Dec 2012
~cellfun('isempty', C) is faster than ~cellfun(@isempty, C), while the anonymous function in cellfun(@(x) ~isempty(x)) is slower.
More Answers (0)
See Also
Categories
Find more on Whos 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!