Remove space in a string while parting data using sscanf.

5 ビュー (過去 30 日間)
Allen Hammack
Allen Hammack 2022 年 4 月 24 日
コメント済み: Allen Hammack 2022 年 4 月 24 日
I am reading a file that has this line:
Pressure Offsets: -0.206,-0.025,0.004 ,-0.099,-0.598
There is an extra space after "0.004" that I would like to remove before parsing the data using a while loop. The particular portion of interest in my while loop is
elseif ((length(tline)>15) && isequal(tline(1:16),'Pressure Offsets'))
pressure_offset_wse_proto = sscanf(replace(sscanf(tline,'%*s %*s %s'),',',' '),'%f')
This code works fine when there is no space after the "0.004", so I'd like to modify this section of my script to automatically remove any spaces between the numbers in the line. I have many separate files to parse using my script, so I need to programmatically remove any extra spaces (or parse the data with the extra space included). Can someone please tell me how to do this?
Thanks!

採用された回答

the cyclist
the cyclist 2022 年 4 月 24 日
編集済み: the cyclist 2022 年 4 月 24 日
Here is a radically different approach, using regexp instead of sscanf:
tline = "Pressure Offsets: -0.206 ,-0.025,0.004 ,-0.099,-0.598";
pressure_offset_wse_proto = double(regexp(tline,["-?\d+\.?\d*"],"match"))'
pressure_offset_wse_proto = 5×1
-0.2060 -0.0250 0.0040 -0.0990 -0.5980
This will work regardless of the presence of multiple extra spaces (like I inserted).
The regular expression returns all strings that have these elements, in order
  • minus sign (or not)
  • one or more digits
  • decimal point (or not)
  • zero or more digits
Then I use double() to convert that string array into numeric.
  3 件のコメント
the cyclist
the cyclist 2022 年 4 月 24 日
My code assumed an input string, rather than a character array. A quick & dirty way to do this is to convert it:
pressure_offset_wse_proto = double(regexp(string(tline),["-?\d+\.?\d*"],"match"))';
Allen Hammack
Allen Hammack 2022 年 4 月 24 日
Everything works now! Thank you, @the cyclist!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by