Parse a String Properly from a Cell Array

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?

 采纳的回答

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 个评论

Hey, thanks so much. This is really great. I think it'll help a lot.
Unfortunately, the 'Factors' data though has multiple different formats. Some of the data is two columns, some is 4 columns. But I think this will help for sure to get me started. Thanks again.
-Jason
My pleasure!
My code does not distinguish between 2-, 3- and 4-column cells. It converts them all correctly, because it only tests for the ‘newline’ '\n' character between lines (rows) of your cell data.
I ran it for all your cells, and it appeared to return the correct data, with either 2, 3, or 4 columns.
If my Answer solves your problem, please Accept it.
Your absolutely correct. Thank you. Sorry for the mistake.
-Jason
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 个)

类别

帮助中心File Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by