C.Colden
C.Colden

Reputation: 627

Make a MatLab table out of 2 Cell Array

What is the most efficient way to generate a table from 2 cell arrays. Array A contains data and Array B contains the corresponding names. I would like to combine them into a convenient table structure.

Cell_Array_A =
{[10x10],[10x10],[];
 [10x11],[],[10x12];
 [9x10],[13x10],[]}

Cell_Array_B = 
{['A','B',[];
 'B',[],'A';
 'B','A',[]}

It should generate a table with the headers 'A' and 'B'. However, in my real data set, I have a lot of variable names, which I don't know. So I need a way to read all variables from the first row and use them to create the table for the rest of the matrix.

Example of the desired output:

'A' 'B'
[10x10] [10x10]
[10x12] [10x11]
[13x10] [9x10]

I tried so far to process the arrays row wise to get rid of the empty arrays. However this is not very efficient. I run the following code for each row in Array A and B. Below an example for the first row in Array A which I later on use as the tablet for my table.

order_row = {};
order_row = Cell_Array_A(1,:);
ordered_filenames = order_row(~cellfun('isempty',order_row));

Upvotes: 1

Views: 178

Answers (1)

user2271770
user2271770

Reputation:

Edited answer The idea is 1) to collect the non-empty column headers, 2) for each unique column header collect the corresponding values:

    % Unique variable names
    nul_names = cellfun(@isempty,Cell_Array_B);
    var_names = unique(Cell_Array_B(~nul_names));

    % Function to find a column header index
    ixhead = @(h,c) cellfun(@(x) isequaln(x,h), c(:));

    % Collect the values
    var_values = cellfun( ...
       @(h) Cell_Array_A(ixhead(h, Cell_Array_B)), var_names, ...
       'UniformOutput', false ...
    );

    % Create the table
    tbl = table(var_values{:}, 'VariableNames', var_names);

Upvotes: 2

Related Questions