Converting cell to array data with specific string
显示 更早的评论
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 个评论
Cris LaPierre
2022-11-16
Please attach your file (or a representative example) to your post using the paperclip icon.
Publius
2022-11-16
采纳的回答
更多回答(2 个)
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 个评论
Publius
2022-11-17
Cris LaPierre
2022-11-17
In that case, Stephen23's answer is better in my opinion
Publius
2022-11-17
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 个评论
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!