Converting cell to array data with specific string
1 view (last 30 days)
Show older comments
Hi,
I am trying to convert data read from a file to a numeric array. The format that it comes in as from an importdata command is:
{'[2, 11, 5, 0] ' }
{'[1, 10, 6, 0] ' }
{'[9, 3, 6, 0] ' }
{'[8, 1, 4, 0] ' }
{'[2, 4, 7, 0] ' }
{'[1, 3, 6, 0] ' }
{'[2, 3, 5, 0] ' }
{'[1, 2, 4, 0] ' }
{'[1, 2, 3, 0] ' }
I want to convert this to a double array of size n by 4. I want to do so without loops, preferably in one line (combined with the importdata command) to keep my code relatively concise. I have tried string, but that spits out an odd answer.
The data file includes those brackets, so I guess if anyone knows how to exclude MATLAB reading those, readmatrix can work (right now, the first and last columns are NaN because of those if I use that command).
Thank you!
2 Comments
Cris LaPierre
on 16 Nov 2022
Please attach your file (or a representative example) to your post using the paperclip icon.
Accepted Answer
Stephen23
on 17 Nov 2022
The simplest approach:
M = readmatrix('test.txt', 'TrimNonNumeric',true)
0 Comments
More Answers (2)
Cris LaPierre
on 16 Nov 2022
Edited: Cris LaPierre
on 16 Nov 2022
There are many ways to do this. Here are two. The result of the 2nd option is a table. See this page on Accessing Data in Tables
file = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1195758/test.txt';
data1 = readmatrix(file,'delimiter',["[","]",","," "],'ConsecutiveDelimitersRule','join',...
'LeadingDelimitersRule','ignore')
data2 = readtable(file,'format','%*c %f %f %f %f %*c')
3 Comments
Jan
on 16 Nov 2022
Edited: Jan
on 16 Nov 2022
data = {'[2, 11, 5, 0] '; '[1, 10, 6, 0] '; '[9, 3, 6, 0] '};
value = str2num(sprintf('%s;', data{:}))
Internally str2num is based on eval. Maybe this is mor secure:
data2 = erase(string(data), "[");
data2 = replace(data2, "]" | ",", " ");
s = strjoin(data2);
value = reshape(sscanf(s, '%g'), 4, []).'
1 Comment
Steven Lord
on 17 Nov 2022
If you're using release R2022a or later you can specify Evaluation='restricted' to limit what expressions in the text to be converted are executed.
str2num('[1, 2; 3, 4; 5:6]', Evaluation='restricted')
To preemptively answer your next question no, I don't have a definitive list of what counts as "basic math expressions" for purposes of restricted evaluation. I suspect if you stick to the operators in the Arithmetic Operators, Relational Operators, and Logical Operators sections on this documentation page along with array creation characters like square brackets, comma, semicolon, and colon you're probably okay.
See Also
Categories
Find more on Structures 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!