Trouble using sscanf to find numbers in a string?

5 ビュー (過去 30 日間)
Olivia Colombo
Olivia Colombo 2019 年 2 月 20 日
コメント済み: Akira Agata 2019 年 2 月 20 日
I'm new to using sscanf, and I'm trying to find the numbers within sentences that contain a temperature. Where it finds an F it converts the temp to celsius, then puts all the temperatures in a new array. The file is attached below. Thanks!
  1 件のコメント
Akira Agata
Akira Agata 2019 年 2 月 20 日
Could you upload TemperatureRecord.txt to test your code?

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

回答 (1 件)

Akira Agata
Akira Agata 2019 年 2 月 20 日
編集済み: Akira Agata 2019 年 2 月 20 日
Thank you for uploading your data file!
How about the following?
% Read data file
fid = fopen('TemperatureRecord.txt','r');
s = textscan(fid,'%s','Delimiter','\r\n');
s = s{1};
fclose(fid);
% Remove leading and trailing space from each line
s = strip(s);
% Remove final ./!/?, if line ends with one of them
s = regexprep(s,'(\.|\!|\?)$','');
% Index where sentence ends with F/f/Fahrenheit/fahrenheit
idxF = endsWith(s,{'F','f','Fahrenheit','fahrenheit'});
% Extract number only
A = regexp(s,'[0-9\.]+','match');
% Convert to doulbe
A = cellfun(@str2double,A);
% Convert F to C
A(idxF) = (A(idxF) - 32)*(5/9);
  2 件のコメント
Stephen23
Stephen23 2019 年 2 月 20 日
編集済み: Stephen23 2019 年 2 月 20 日
This will not work on linux (or on many files written by applications on Windows that do not insert useless carriage returns). Two simple adjustments make this work for all OS and all files:
fid = fopen('TemperatureRecord.txt','rt'); % rt
s = textscan(fid,'%s','Delimiter','\n'); % \n
fclose(fid);
s = s{1};
Akira Agata
Akira Agata 2019 年 2 月 20 日
Hi Stephen-san,
Oh, I have been assuming running it on Windows, only.
Thank you for your useful comment!

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by