How to read and stores values from certain number of lines followed by a line starting as TS in a .txt file?

조회 수: 2 (최근 30일)
Hi everyone,
Every time after the line starting as TS (in the attached datap.txt), I want to read the 1st, 5th, 19th, 33th, 47th and 52th lines.
Here, line number counted after TS, like (-9.19000000e+00=1st line) and (3.74000000e+00 = 5th line) after first TS line (TS 0 0.00000000e+00).
Accordingly, (-9.19000000e+00 = 1st line) and (4.06626222e+00 = 5th line) after 2nd TS line (TS 0 3.62884792e+03).
I also want to store all 1st line values in a vector
d1 = [-9.19000000e+00 -9.19000000e+00 .........]
5th line values in another vector
d5 = [3.74000000e+00 4.06626222e+00 ............] and so on.
In another vector I want to grab the numeric values at the end of TS lines, like
TS = [0.00000000e+00 3.62884792e+03 .........]
Can anyone please help me in this regard.
Thanks a lot :)

채택된 답변

Preyanka Dey
Preyanka Dey 2020년 10월 2일
편집: Preyanka Dey 2020년 10월 2일
I solved...following is the answer if anyone need it....
function main
A = regexp(fileread('datap.txt'),'\n','split');
Whichline = find(~cellfun('isempty',...
strfind(A,'TS 0 ')))
gage5 = [];
gage10 = [];
gage13 = [];
gage19 = [];
TS_sec = [];
idx=[Whichline];
n = length(idx);
for i = 1:n
TimeStp = regexp(A{idx(i)},' ','split');
TS_sec = [TS_sec; TimeStp{4}];
gage5 = [gage5; A{idx(i)+5}];
gage10 = [gage10; A{idx(i)+10}];
gage13 = [gage13; A{idx(i)+13}];
gage19 = [gage19; A{idx(i)+19}];
end
gage5_m= str2num(gage5);
gage10_m= str2num(gage10);
gage13_m= str2num(gage13);
gage19_m= str2num(gage19);
T_sec= str2num(TS_sec);
%1st Option
gtable = table(T_sec, gage5_m, gage10_m, gage13_m, gage19_m);
writetable(gtable,'gtable.dat','WriteVariableNames',true);
write_files('Sroy.dat', T_sec, gage5_m, gage10_m, gage13_m, gage19_m);
end
function write_files(fname, T_sec, gage5_m, gage10_m, gage13_m, gage19_m)
fid = fopen(fname, 'w');
fprintf('%f %f %f %f %f\n',[T_sec gage5_m gage10_m gage13_m gage19_m]');
fprintf(fid,'%f %f %f %f %f\n',[T_sec gage5_m gage10_m gage13_m gage19_m]');
fclose(fid);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Classical Control Design에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by