Hi there,
Just wondering how to convert some matrix string (such as A = '[1,2,3,4,5]') into a numerical matrix (like [1,2,3,4,5]) so that it displays when entered into matlab like,
ans =
1 2 3 4 5
instead of
Columns 1 through 5
1.0000 2.0000 3.0000 4.0000 5.0000
Cheers,
Samuel

 채택된 답변

madhan ravi
madhan ravi 2020년 10월 10일
편집: madhan ravi 2020년 10월 10일

1 개 추천

Normally str2num() is not suggested:
Wanted = sscanf(A(2:end-1), '%d').' % edited after sir Walter’s comment to exclude []

댓글 수: 5

The [] and comma interfere with sscanf unless you program for them
A = '[1,2,3,4,5]'; sscanf(A(2:end-1), '%d,')
madhan ravi
madhan ravi 2020년 10월 10일
Ah, thank you sir Walter, I just typed straight away.
Samuel Lee
Samuel Lee 2020년 10월 10일
Thank you Madhan and Walter, this is cool. How do you adapt the code if there were no commas seperating the values? E.g. A = '[1 0.2 0.4 0.5 0.6]'
Cheers
A = '[1 0.2 0.4 0.5 0.6]'; sscanf(A(2:end-1), '%f')
ans = 5×1
1.0000 0.2000 0.4000 0.5000 0.6000
If the problem is that you might have commas or might not then:
A = '[1 0.2, 0.4, 0.5 0.6]'; sscanf(A(2:end-1), '%f%*[, ]')
ans = 5×1
1.0000 0.2000 0.4000 0.5000 0.6000
Samuel Lee
Samuel Lee 2020년 10월 10일
Cheers Walter, this is awesome. I couldn't quite work it out from the page (https://au.mathworks.com/help/matlab/ref/sscanf.html).
Thank you!

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

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 10월 10일
편집: Ameer Hamza 2020년 10월 10일

1 개 추천

A = '[1,2,3,4,5]';
A = str2num(A);
Result
>> A
A =
1 2 3 4 5
Another alternative which is generally not recommended, but can be useful here
A = '[1,2,3,4,5]';
A = eval(A);

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2020년 10월 10일

댓글:

2020년 10월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by