MATLAB: How to convert array of chars examples: ’09:56am’ or ’09:56pm’ to number

array. char. pm. am. number. string.

I have a problem. I need to find if char contains 'am' or 'pm' in it. I have a string '08:09am' and '12:02pm'. Problem is that this is packed in array of 256 simmilar strings. My task is to covert this strings to numbers but i can't really do it.

Best Answer

Assuming that you want to convert those char vectors into hours since midnight, then this works:
C = {'08:09am','12:02pm','01:0pm','0:0am'};
T = regexpi(C,'^(\d+):(\d+)([ap])m$','once','tokens');
T = cell2mat(cellfun(@(t)t(:).',T(:),'uni',0));
M = str2double(T(:,1:2))
P = strcmpi(T(:,3),'P') & M(:,1)<12
Z = (P*12+M(:,1)+M(:,2)/60)/24
giving:
Z =
0.33958
0.50139
0.54167
0.00000