Converting a string into a numerical array
26 ビュー (過去 30 日間)
古いコメントを表示
How to conver a string in the form "[1,2,3,4,5]"
into a vector 1 2 3 4 5
I have used strrep command but here I have to remove each of the "[", "]", ",", sepreately and the convert it into a numaerical vector.
Is there any other simple solution (might be in one or two lines) for this conversion
1 件のコメント
Stephen23
2020 年 3 月 1 日
編集済み: Stephen23
2020 年 3 月 1 日
Judging by your earlier question
the simplest solution is to avoid this situation entirely by not saving data in such a pointlessly inefficient format.
Saving in a standard binary or text format would mean you could trivially use basic import/export functions, without any of the inefficient code that you have decided to use.
採用された回答
その他の回答 (1 件)
Stephen23
2020 年 3 月 1 日
Much more efficient than the accepted answer:
>> str = '[1,2,3,4,5]';
>> vec = sscanf(str(2:end),'%f,',[1,Inf])
vec =
1 2 3 4 5
This also avoids the evil eval hidden inside str2num.
2 件のコメント
darova
2020 年 3 月 1 日
- This also avoids the evil eval hidden inside str2num.
I opened sscanf function and only see comments. How do you know?
dpb
2020 年 3 月 1 日
編集済み: dpb
2020 年 3 月 1 日
It's in the documentation...
"... str2num uses the eval function, which can cause unintended side effects when the input includes a function name. To avoid these issues, use str2double."
Unfortunately, to take that advice takes some more effort as
>> str2double(extractBetween("[1,2,3,4,5]",'[',']'))
ans =
12345
>>
To avoid that,
>> str2double(split(extractBetween("[1,2,3,4,5]",'[',']'),',')).'
ans =
1 2 3 4 5
>>
I just took the easy way out.
And, of course, if performance is a real issue, then it is definitely true that sscanf is going to win hands down on big strings, but probably rare cases that it would actually ever show up as a bottleneck.
It's just a simple way w/o having to remember format string syntax, etc., and illustrates some of the newer string functions.
ADDENDUM:
And, since the OP used a string notation in his example, I presumed it would be such in his code; Stephen wrote his test string as a char() string array, not as a string() array element. To do that means more work, too:
> sscanf(s{1}(2:end),'%f,',[1 inf])
ans =
1 2 3 4 5
>>
as sscanf and friends aren't string awares...the string functions and str2xxx are.
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!