Converting a string into a numerical array
28 次查看(过去 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!