Convert String to Numerical Matrix

3 views (last 30 days)
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

Accepted Answer

madhan ravi
madhan ravi on 10 Oct 2020
Edited: madhan ravi on 10 Oct 2020
Normally str2num() is not suggested:
Wanted = sscanf(A(2:end-1), '%d').' % edited after sir Walter’s comment to exclude []
  5 Comments
Samuel Lee
Samuel Lee on 10 Oct 2020
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!

Sign in to comment.

More Answers (1)

Ameer Hamza
Ameer Hamza on 10 Oct 2020
Edited: Ameer Hamza on 10 Oct 2020
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);

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by