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 Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by