Converting a string into a numerical array

13 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 1 Mar 2020
Edited: Stephen23 on 1 Mar 2020
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.

Sign in to comment.

Accepted Answer

dpb
dpb on 1 Mar 2020
v=str2num(extractBetween("[1,2,3,4,5]",'[',']'));

More Answers (1)

Stephen23
Stephen23 on 1 Mar 2020
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 Comments
darova
darova on 1 Mar 2020
  • This also avoids the evil eval hidden inside str2num.
I opened sscanf function and only see comments. How do you know?
dpb
dpb on 1 Mar 2020
Edited: dpb on 1 Mar 2020
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.

Sign in to comment.

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!