Loop for reading and extracting data from a single line of multiple text files.

조회 수: 2 (최근 30일)

I have the following code that I would like to put into a loop to read multiple text files.

txt = fileread('Test01.txt');
  temppos = strfind(txt,'Ground Temperature:');
  endpos = strfind(txt, '°C');
    for k = 1:numel(temppos)
        section{k,:} = txt(temppos(k):endpos(k));
    end
    for k = 1:numel(section)
        temp(k,:) = sscanf(section{k}, 'Ground Temperature: %f');
    end
    Results = table(temp, 'VariableNames',{'Temp'});
  댓글 수: 2
James
James 2024년 9월 16일
이동: Voss 2024년 9월 16일
Please see the files attached.
James
James 2024년 9월 16일
이동: Voss 2024년 9월 16일
Having issues saving multiple files. Could only save one. But the only thing changing in the data is the file name and the temp.

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2024년 9월 16일
편집: Star Strider 2024년 9월 16일
I generally do something like this —
files = dir('*.txt');
for k = 1:numel(files)
txt = fileread(files(k).name);
temppos = strfind(txt,'Ground Temperature:');
endpos = strfind(txt, '°C');
for k = 1:numel(temppos)
section{k,:} = txt(temppos(k):endpos(k));
end
for k = 1:numel(section)
temp(k,:) = sscanf(section{k}, 'Ground Temperature: %f');
end
Results{k} = table(temp, 'VariableNames',{'Temp'});
end
Results{:}
ans = table
Temp ____ 29.3
This assumes the files are already in your working directory and on your MATLAB search path.
If that is not the situation in your application, you will need something like this:
files = dir('C:\PathName\*.txt')
and then:
filename{k} = fullfile('C:\PathName\',files(k).name)
text = fileread(filename{k});
or something similar. It may be neecessary for you to experiment a bit, depending on your situation.
EDIT — Corrected typographical errors.
.
  댓글 수: 13

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by