textscan - multiple format lines

12 ビュー (過去 30 日間)
Vahideh Ansari Hosseinzadeh
Vahideh Ansari Hosseinzadeh 2021 年 8 月 4 日
コメント済み: Rik 2021 年 8 月 4 日
I have a txt file with these data:
Dose Cycle = 1
Dosing Time (ms) = 57
Start Pressure (psi) = 0.00
End Pressure (psi) = 0.05
Battery Start Voltage (mV) = 10
Battery End Voltage (mV) = 110
I want to read this file and extract these info.
fid = fopen('nums1.txt');
C = textscan(fid, '%s %s %s %s %s %f\n');
But each line has different fromat, how can I do this for each line?
Can anyone offer any suggestions.
Thanks!

採用された回答

Rik
Rik 2021 年 8 月 4 日
編集済み: Rik 2021 年 8 月 4 日
It looks like the same format to me. Why not read as text, split on the = and use str2double on the last column?
To read your file to a cell array you can use my |readfile| function link. If you're on R2020b or later you can use readlines instead (which will return a string vector, but split will still work).
txt={'Dose Cycle = 1'
'Dosing Time (ms) = 57'
'Start Pressure (psi) = 0.00 '
'End Pressure (psi) = 0.05 '
'Battery Start Voltage (mV) = 10'
'Battery End Voltage (mV) = 110'};
res=split(txt,'=')
res = 6×2 cell array
{'Dose Cycle ' } {'→ 1' } {'Dosing Time (ms) ' } {'→57' } {'Start Pressure (psi) '} {'→ 0.00 '} {'End Pressure (psi) '} {'→ 0.05 '} {'Battery Start Voltage (mV) '} {'→ 10' } {'Battery End Voltage (mV) '} {'→ 110' }
str2double(res(:,2))
ans = 6×1
1.0000 57.0000 0 0.0500 10.0000 110.0000
  2 件のコメント
Vahideh Ansari Hosseinzadeh
Vahideh Ansari Hosseinzadeh 2021 年 8 月 4 日
編集済み: Vahideh Ansari Hosseinzadeh 2021 年 8 月 4 日
Thanks for your reply. Is it possible to use MATLAb built-in function? Because I have some headers, several blocks in txt file, that I'm going to work on.
Rik
Rik 2021 年 8 月 4 日
readlines is builtin, and it is easy to download my readfile function (on R2017a and newer you can even use the AddOn Manager).
So I don't know if I fully understand what your problem is with my suggestion.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEnergy Production についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by