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개)
Cris LaPierre
2022년 11월 16일
편집: Cris LaPierre
2022년 11월 16일
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!