Reading single value from text file

9 ビュー (過去 30 日間)
Ted McG
Ted McG 2020 年 9 月 21 日
回答済み: Ruger28 2020 年 9 月 21 日
Hello all,
I am reading in text files of the following format and would like to extract just the Peak frequency value (6.8 below) and put it into an array. What is the easiest way to do this? Thanks, fairly new to MATLAB.
Vibration Test
9/16/2020 2:12:25 PM
Sample Rate (Hz) = 2000.00
Peak frequency (Hz) = 6.8 Resolution (Hz) = 0.2
  2 件のコメント
Ruger28
Ruger28 2020 年 9 月 21 日
Will this sample be the only thing in each file? Meaning you might have 50 or so files that look just like this?
Ted McG
Ted McG 2020 年 9 月 21 日
yes

サインインしてコメントする。

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 9 月 21 日
編集済み: Ameer Hamza 2020 年 9 月 21 日
Try this
str = fileread('data.txt');
peak_freq = regexp(str, 'Peak frequency \(Hz\) =[\s\t]*(\d*\.\d*)', 'tokens');
peak_freq = str2double(peak_freq{1}{1});
data.txt file is attached.

その他の回答 (1 件)

Ruger28
Ruger28 2020 年 9 月 21 日
One approach, which only works if these files dont change would be to read in and point to directly where the value is.
fname = 'C:\Users\<username>\Desktop\SampleFile.txt';
FID = fopen(fname);
x = textscan(FID,'%s');
fclose(FID);
freqVal = str2double(x{1,1}{15,1});
This looks directly at the location of the freq, that is if this file format never changes. Another method would be to use fgetl to extract each line, and search for your key terms, such as:
fname = 'C:\Users\<username>\Desktop\SampleFile.txt';
FID = fopen(fname);
loopcnt = 1;
while loopcnt
temp = fgetl(FID);
if any(strfind(temp,'Peak frequency (Hz) ='))
startI = regexp(temp,'=','once');
stopI = regexp(temp,'Resolution','once');
Freq = str2double(strtrim(temp(startI+1:stopI-1)));
break
end
end
fclose(FID);

カテゴリ

Help Center および File ExchangeDimensionality Reduction and Feature Extraction についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by