Parse a String Properly from a Cell Array
조회 수: 11 (최근 30일)
이전 댓글 표시
I have a cell array named "Factors". It is 617 x 1. Each cell contains a string consisting of a 2 column headers and then two columns of data over 1000 rows long. I am having trouble getting the MATLAB to parse this properly.
If I open the variable in the variable editor, I can copy a single cell and paste it to Excel, and excel is capable of sorting the data properly. Two columns, 1000+ rows, exactly how i need to see it.
However, when I try to manipulate the data in MATLAB to try and pull out particular data or at least get it into a form where I can do something with it, I can't get it. I have tried to use strsplit but it is not cooperating. Does anyone have a suggestion?
댓글 수: 0
채택된 답변
Star Strider
2016년 2월 15일
Your ‘Factors’ cell array are strings, so getting the numeric data is not as straightforward as it might otherwise be. You can adapt this code in a loop over the various cells to retrieve and work on those you want.
D = load('Jason Allnutt Factors.mat');
F = D.Factors;
F1 = F{1}; % Get First Cell (Example)
FrqAmp = F1;
Parse = regexp(FrqAmp, '\n', 'split')'; % Split Strings By NewLine ‘\n’
NumData = cell2mat(cellfun(@str2num, Parse, 'Uni',0)); % Recover Numeric Matrix
See_Results = NumData(1:5,:) % Recovered Data Sample (Delete)
See_Results =
0.01 11.16
0.02 6.07
0.03 3.7
0.04 2.44
0.05 1.7
If you want all of them in a numeric cell array, just loop through all of them and save them as numeric cells.
D = load('Jason Allnutt Factors.mat');
F = D.Factors;
for k1 = 1:size(F,1)
Parse = regexp(F{k1}, '\n', 'split')'; % Split Strings By NewLine ‘\n’
NumData{k1} = cell2mat(cellfun(@str2num, Parse, 'Uni',0)); % Recover Numeric Matrix & Store In ‘NumData’
end
It takes a while to loop through them, so be patient with it. I would save the results (the ‘NumData’ cell array) as a separate .mat file so you can just load them and don’t have to parse them each time.
댓글 수: 4
Star Strider
2016년 2월 17일
My pleasure.
No worries — your array is so large that without parsing it, there’s no way to know the dimensions of the various cells.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!