MATLAB Answers

Consolidate Substring Code using Cellfun

5 views (last 30 days)
Ms. Mat
Ms. Mat on 23 Dec 2012
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 !

Accepted Answer

Laura Proctor
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
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by