How to create an array of integers from a string

2 ビュー (過去 30 日間)
W
W 2014 年 8 月 12 日
回答済み: Jan 2014 年 8 月 12 日
Hi everyone, I have a string of the form: 'm:n, i, j' and I want to create an array with those integers. For example, if my string was '1:3, 10, 11' then the desired array would be [1, 2, 3, 10, 11]. I've tried using the eval function but couldn't figure out how to assign the result of eval to an array. Does anyone have any suggestions?

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 12 日
編集済み: Azzi Abdelmalek 2014 年 8 月 12 日
s='1:3, 10, 11'
out=str2num(s)
With eval it should be something like
s='1:3, 10, 11'
eval(strcat('out=[', s ,']'))
  2 件のコメント
W
W 2014 年 8 月 12 日
Thank you! I had tried using str2num earlier when the string was formatted a little differently and hadn't thought to try it again. It works great!
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 12 日

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

その他の回答 (1 件)

Jan
Jan 2014 年 8 月 12 日
Reduce the use of EVAL as far as possible:
s = '1:3, 10, 11'
out = eval(['[', s, ']']);
If the format is strictly 'm:n, i, j', this would be cleaner than eval:
d = sscanf(s, '%g:%g, %g, %g')
out = [d(1):d(2), d(3), d(4)]

カテゴリ

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