필터 지우기
필터 지우기

Consolidate Substring Code using Cellfun

조회 수: 4 (최근 30일)
Ms. Mat
Ms. Mat 2012년 12월 23일
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 !

채택된 답변

Laura Proctor
Laura Proctor 2012년 12월 23일
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
Jan
Jan 2012년 12월 24일
~cellfun('isempty', C) is faster than ~cellfun(@isempty, C), while the anonymous function in cellfun(@(x) ~isempty(x)) is slower.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by