MATLAB: Read mixed numbers in Matlab

read mixed numbers in matlab

Dear Sir/Madam,
I have a data file containing text and mixed number like this: (see the file attached data.txt.)
AA, BB, 28 21/64, 28 45/64,
AA, BB, 1/64, 11/64,
the mixed number have format:
integer space numerator/denominator
I would like to read the data file in matlab as
AA, BB, 28.328125, 28.703125,
AA, BB, 0.015625, 0.171875,
i. e. read mixed numbers and convert them into decimal numbers.
What Matlab command to use? I would greatly appreciate it if you left your code and running output.
I am using MATLAB R2014a.
Thank you

Best Answer

opt = {'CollectOutput',true,'Delimiter',','};
fmt = repmat('%s',1,4);
[fid,msg] = fopen('data.txt','rt');
assert(fid>=3,msg);
C = textscan(fid,fmt,opt{:})
fclose(fid);
C = C{1}; % raw character data in a cell array.
% Convert fractions to numeric:
foo = @(v) sum([v(1:end-2),v(end-1)/v(end)]);
baz = @(s) foo(sscanf(s,'%d%*[ /]'));
M = cellfun(baz,C(:,3:4))
Giving:
M =
28.328125 28.703125
0.031250 0.046875
and the string data is in C. If you want the numeric data reinserted back into C then use num2cell:
>> C(:,3:4) = num2cell(M)
C =
'AA' 'CC' 28.328125 28.703125
'AA' 'CC' 0.031250 0.046875