How can I read from a file (specific format) using Matlab?
Afficher commentaires plus anciens
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!
Réponses (2)
Mathieu NOE
le 14 Mai 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]}
str = fileread('temp.txt');
rgx = ':scurrent:(.+?):t:(.+?):c:(.+?):';
tkn = regexp(str,rgx,'tokens');
tkn = vertcat(tkn{:})
mat = str2double(tkn(:,2:3)) % optional
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!