Consolidate Substring Code using Cellfun
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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
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 Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!