MATLAB Answers

How can I read from a file (specific format) using Matlab?

1 view (last 30 days)
Marios Ermogenous
Marios Ermogenous on 13 May 2021
Edited: Stephen Cobeldick on 14 May 2021
Hello everyone, I have a file which contains (something like this):
(MM):2:scurrent:OOTr1:t:0:c:-6.09249419808415990234375000e+00:
(MM):2:scurrent:OOTr1:t:1:c:-1.504382440400277657500976562e-01:
(MM):2:scurrent:OOTr4:t:0:c:-1.8307473939608802050712500000e-09:
(MM):2:scurrent:OOTr4:t:1:c:-2.0431058377931707220459843750e-01:
(MM):2:scurrent:SOTr1:0:t:0:c:1.405659077717170715332031250e-01:
(MM):2:scurrent:SOTr1:0:t:1:c:-1.492715471683210969543457031e-02:
(MM):2:scurrent:SSTr1:0:3:t:3:c:-4.365555129264354705810546875e-03:
(MM):2:scurrent:SSTr4:0:4:t:0:c:-3.780450239996445175595703125e-01:
....
and I would like to read from it only the bold face quantities and make three matrices which correspond to these columns. How can I do that?
Thanks in advance!

Answers (2)

Mathieu NOE
Mathieu NOE on 14 May 2021
hello
here you are :
T = readlines('data.txt');
for ci = 1:numel(T)
Tci = T(ci);
str1{ci,1} = char(extractBetween(Tci,':scurrent:',':t:'));
num1{ci,1} = str2num(extractBetween(Tci,':t:',':c:'));
tmp = findstr(Tci,':');
Tcic = char(Tci);
num2{ci,1} = str2num(Tcic(tmp(end-1)+1:tmp(end)-1));
end
Out = [str1 num1 num2];
% will give following results :
% Out =
%
% 8×3 cell array
%
% {'OOTr1' } {[0]} {[ -6.0925]}
% {'OOTr1' } {[1]} {[ -0.1504]}
% {'OOTr4' } {[0]} {[-1.8307e-09]}
% {'OOTr4' } {[1]} {[ -0.2043]}
% {'SOTr1:0' } {[0]} {[ 0.1406]}
% {'SOTr1:0' } {[1]} {[ -0.0149]}
% {'SSTr1:0:3'} {[3]} {[ -0.0044]}
% {'SSTr4:0:4'} {[0]} {[ -0.3780]}

Stephen Cobeldick
Stephen Cobeldick on 14 May 2021
Edited: Stephen Cobeldick on 14 May 2021
str = fileread('temp.txt');
rgx = ':scurrent:(.+?):t:(.+?):c:(.+?):';
tkn = regexp(str,rgx,'tokens');
tkn = vertcat(tkn{:})
tkn = 8×3 cell array
{'OOTr1' } {'0'} {'-6.09249419808415990234375000e+00' } {'OOTr1' } {'1'} {'-1.504382440400277657500976562e-01' } {'OOTr4' } {'0'} {'-1.8307473939608802050712500000e-09'} {'OOTr4' } {'1'} {'-2.0431058377931707220459843750e-01'} {'SOTr1:0' } {'0'} {'1.405659077717170715332031250e-01' } {'SOTr1:0' } {'1'} {'-1.492715471683210969543457031e-02' } {'SSTr1:0:3'} {'3'} {'-4.365555129264354705810546875e-03' } {'SSTr4:0:4'} {'0'} {'-3.780450239996445175595703125e-01' }
mat = str2double(tkn(:,2:3)) % optional
mat = 8×2
0 -6.0925 1.0000 -0.1504 0 -0.0000 1.0000 -0.2043 0 0.1406 1.0000 -0.0149 3.0000 -0.0044 0 -0.3780

Community Treasure Hunt

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

Start Hunting!