Converting a string into a numerical array

조회 수: 13 (최근 30일)
Vinay Killamsetty
Vinay Killamsetty 2020년 3월 1일
편집: dpb 2020년 3월 1일
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
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.

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2020년 3월 1일
v=str2num(extractBetween("[1,2,3,4,5]",'[',']'));

추가 답변 (1개)

Stephen23
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
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
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 CenterFile Exchange에서 String에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by