Clear Filters
Clear Filters

What is the simplest way to convert this string '[[x1, x2, x3], [y1, y2, y3], [& so on]]' into a matlab matrix where each item is a row, [x1,x2,x3 ; y1, y2, y3; & so on]?

2 views (last 30 days)
What is the simplest way to convert this string '[[x1, x2, x3], [y1, y2, y3], [& so on]]' into a matlab matrix where each item is a row, [x1,x2,x3 ; y1, y2, y3; & so on]? Thank you!

Accepted Answer

Walter Roberson
Walter Roberson on 23 Jun 2017
S = '[[x1, x2, x3], [y1, y2, y3], [&, so, on]]';
S = S(3:end-2); %get rid of leading and trailing [[ ]]
by_line = regexp(S, '],\s*\[', 'split'); %split at comma between subsections
by_item = regexp(by_line, ',\s*', 'split'); %split each subsection at comma
enmass = vertcat(by_item{:}); %reassemble cell array
output = str2double(enmass);

More Answers (1)

the cyclist
the cyclist on 23 Jun 2017
Similar technique to Walter's:
S = '[[1,2,3],[4,5,16]]';
output = str2num(regexprep(S(3:end-2),'],[',';'));

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!