string to number conversion with mixed values

7 ビュー (過去 30 日間)
lafnath p
lafnath p 2016 年 10 月 25 日
コメント済み: Walter Roberson 2016 年 10 月 26 日
i have two strings
'index_N=10'
and
'index_M=5'
in a file.
how can i get only numbers N =10 and M=5. from these strings

回答 (2 件)

Massimo Zanetti
Massimo Zanetti 2016 年 10 月 25 日
str1 = 'index_N=10'
str2 = 'index_M=5'
sub1 = str1(7:end)
sub2 = str(7:end)
  2 件のコメント
lafnath p
lafnath p 2016 年 10 月 25 日
IT GIVES 10 , 5 AS STRINGS.
but i want those values as integers
Walter Roberson
Walter Roberson 2016 年 10 月 25 日
str2double() or sscanf()

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


Guillaume
Guillaume 2016 年 10 月 25 日
It looks like you're asking two things:
  • how to create variables named from the content of a string,
  • how to get the index string and number from your input string.
The first part is an extremely bad idea, so I won't show you how to do it because it always lead to bad practice, and complicated, buggy and unmaintainable code. If you want to store these names, store them in a cell array, table, or containers.Map.
To extract name and number from your input:
tokens = regexp(inputstring, 'index_(.)=(\d+)', 'tokens', 'once');
indexname = tokens{1}
indexvalue = str2double(tokens{2})
%optionally store them in a map created with
%map = containers.Map;
map(indexname) = map(indexvalue)
%or store them in a table created with:
%t = table({}, [], 'VariableNames', {'IndexName', 'IndexValue'})
t = [t; table(indexname, indexvalue, 'VariableNames', {'IndexName', 'IndexValue'})]

カテゴリ

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