# Converting a string into a numerical array

1 view (last 30 days)
Vinay Killamsetty on 1 Mar 2020
Edited: dpb on 1 Mar 2020
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
Stephen on 1 Mar 2020
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.

dpb on 1 Mar 2020
v=str2num(extractBetween("[1,2,3,4,5]",'[',']'));
Vinay Killamsetty on 1 Mar 2020
Thank you very much

Stephen 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 CommentsShowHide 1 older comment
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.
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.

R2019a

### Community Treasure Hunt

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

Start Hunting!