Terry Cai
Terry Cai

Reputation: 35

How can I convert this table to a cell array as shown in the screenshot?

I am trying to convert a table imported from a CSV file (see below) and convert it to two cell arrays. As shown in the screenshots, Cell 1 contains "measure" of he table, measures of the same ID go in the same cell. Similarly Cell 2 contains "t" in the same way.

Matlab is not my language but I have a function to test out written in Matlab only, so I am really unsure how I could achieve this task.

Table

Cell 1

Cell 2

Upvotes: 0

Views: 250

Answers (2)

Terry Cai
Terry Cai

Reputation: 35

In case someone is interested in my non-Matlab solution to the problem:

array_id=table2array(data(:,'id'));
array_t=table2array(data(:,'t'));
array_measure=table2array(data(:,'measure'));
uni_id=unique(array_id);

t_cell=cell(1,length(uni_id));
measure_cell=cell(1,length(uni_id));

for i=1:length(uni_id)
    temp_t=table2array(data(data.id==uni_id(i),'t'));
    temp_measure=table2array(data(data.id==uni_id(i),'measure'));

    t_cell{i}=temp_t';
    measure_cell{i}=temp_measure';
end

Apparently this is nothing comparable to what Luis has, but it gets the job done.

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112769

Let the data be defined as

data = array2table([1 100 1; 1 200 2; 1 300 3; 2 500 3; 2 600 4; 2 700 5; 2 800 6], ...
       'VariableNames', {'id' 'measure' 't'}); % example data

You can use findgroups and splitapply as follows:

g = findgroups(data.id); % grouping variable
result_measure = splitapply(@(x){x.'}, data.measure, g).'; % split measure as per g
result_t = splitapply(@(x){x.'}, data.t, g).'; % split t as per g

Alternatively, findgroups for a single grouping variable can be replaced by unique (third output), and splitapply for a single data variable can be replaced by accumarray:

[~, ~, g] = unique(data.id); % grouping variable
result_measure = accumarray(g, data.measure, [], @(x){x.'}).'; % split measure as per g
result_t = accumarray(g, data.t, [], @(x){x.'}).'; % split t as per g

Upvotes: 1

Related Questions