MATLAB Answers

Creating Table from Cell Array Data

26 views (last 30 days)
Ben
Ben on 22 Sep 2020 at 23:34
Edited: Adam Danz on 23 Sep 2020 at 11:25
Hi All,
I am trying to create a table from data stored in a Cell array . The cell array is 1x3 specified as follows:
SelectNewVectorCell = {[1;2;3;4;5;6;9;88], [11;22;23;25;66;88], [33;55;66;7;8;9]};
I then try to create the table using the following code. Unfortunately, I can only get it to output the final column of the cell array to the table (it seems to be overwriting…)
le = length(SelectNewVectorCell)
names(1,1:le) = {'Bin1'};
rows1 = cellfun(@(M) size(M,1), SelectNewVectorCell);
cols1 = cellfun(@(M) size(M,2), SelectNewVectorCell);
maxrows1 = max(rows1)
R = table();
for K = 1 : length(SelectNewVectorCell)
R.(names{K}) = [SelectNewVectorCell{K}; nan(maxrows1 - rows1(K), cols1(K))];
end
Interestingly if I change the code slightly to this it seems to work
le = length(SelectNewVectorCell)
% names(1,1:le) = {'Bin1'};
names1 = {'Bin1', 'Bin2', 'Bin3'};
rows1 = cellfun(@(M) size(M,1), SelectNewVectorCell);
cols1 = cellfun(@(M) size(M,2), SelectNewVectorCell);
maxrows1 = max(rows1)
R = table();
for K = 1 : length(SelectNewVectorCell)
R.(names1{K}) = [SelectNewVectorCell{K}; nan(maxrows1 - rows1(K), cols1(K))];
end
Any ideas why the first code fails to write correctly to the table? Thanks
Ben

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 22 Sep 2020 at 23:44
Edited: Adam Danz on 23 Sep 2020 at 11:25
The first version in your question doesn't work because "names" contain 3 VariableNames that are all "Bin1" so when you assign the values within the loop, the first iteration assigns Bin1 to the table but subsequent iterations overwrite that column since you're writing to the same variable name.
The second version of your question avoids that problem but naming the columns differently.
You can create that table with the 3 lines of code below.
SelectNewVectorCell = {[1;2;3;4;5;6;9;88], [11;22;23;25;66;88], [33;55;66;7;8;9]};
maxNumRow = max(cellfun(@(c) numel(c), SelectNewVectorCell)); % max length
mPad = cell2mat(cellfun(@(c){padarray(c,[maxNumRow-numel(c),0],NaN,'Post')},SelectNewVectorCell));
R = array2table(mPad, 'VariableNames', compose('Bin%d',1:size(mPad,2)));
Result
R =
8×3 table
Bin1 Bin2 Bin3
____ ____ ____
1 11 33
2 22 55
3 23 66
4 25 7
5 66 8
6 88 9
9 NaN NaN
88 NaN NaN

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by