フィルターのクリア

Extract float from a filename

2 ビュー (過去 30 日間)
K3iTH
K3iTH 2022 年 2 月 24 日
コメント済み: K3iTH 2022 年 2 月 24 日
Hi all,
I have a list of files in a directory with a name of "time_ xx" where xx is number (for e.g 0.20, 0.41, 0.61, 0.82,...) the number is not does not have a fixed expression. I want like to extract these number and used it for calculation later.
May I know what function can I used to extract the number from a filename without extension?
Thank you.

採用された回答

DGM
DGM 2022 年 2 月 24 日
編集済み: DGM 2022 年 2 月 24 日
Well I guess this is one way. There are probably more elegant ways of unpacking the nested cell array and converting to numeric, but this is how I did it.
names = {'time_0.709'
'time_5.61'
'time_0.2081'
'time_45.027'
'time_90'};
filenums = str2double(regexprep(names,'.*_(?=(\d*\.*)+$)',''))
filenums = 5×1
0.7090 5.6100 0.2081 45.0270 90.0000
This looks for any number between an underscore and the end of each name. The filename prefix is ignored except for the underscore.
I guess if you wanted rely on the prefix, you could alternatively just do:
names = {'time_0.709'
'time_5.61'
'time_0.2081'
'time_45.027'
'time_90'};
filenums = str2double(strrep(names,'time_',''))
filenums = 5×1
0.7090 5.6100 0.2081 45.0270 90.0000
  1 件のコメント
K3iTH
K3iTH 2022 年 2 月 24 日
Hi DGM,
Thank you for you help. Both method is very useful. Persoanlly, I seldom use "regexprep" but the second method "strrep" is fast and direct.
Once again, thank you so much!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by