Merge elements of different cells

Suppose we have an array of cells consisting of identifiers and one attribute, for example

A{1,1}=[1 2;2 4]
A{1,2}=[2 3 5;8 5 6] 

Now I would like to have the final output consisting of the unique identifiers of two cells (the values ​​of the first row), and the corresponding columns have the attribute value of each cell separately. those.

C = 
[1]    [         2]
[2]    [1x2 double]  % 4 in first cell and 8 in second cell
[3]    [         5]
[5]    [         6]

it seems impossible to use something like C=[unique(A{1,:}(1,:)')]. Any help is appreciated.

+4
source share
1 answer

, , , , 2D- accumarray. accumarray , , , . , , , , accumarray , .

cell2mat, 2D-, , accumarray . , , , , - , accumarray . , ID 4, 3 5, 6 5 7 ( ). 7, accumarray , ID 1 ID 7 1. , , - accumarray .

, , , .... :

%// Setup
A{1,1}=[1 2;2 4];
A{1,2}=[2 3 5;8 5 6];
A{1,3}=[7;8];

%// Convert row of cell arrays to a single 2D matrix, then transpose for accumarray
B = cell2mat(A).';

%// Group IDs together and ensure they're sorted
out = accumarray(B(:,1), B(:,2), [], @(x) {sort(x)});

%// Add a column of IDs and concatenate with the previous output
IDs = num2cell((1:numel(out)).');
out = [IDs out];

%// Any cells from the grouping that are empty, eliminate
ind = cellfun(@isempty, out(:,2));
out(ind,:) = [];

:

out = 

    [1]    [         2]
    [2]    [2x1 double]
    [3]    [         5]
    [5]    [         6]
    [7]    [         8]

>> celldisp(out(2,:))

ans{1} =

     2         

ans{2} =

     4
     8

, 2D-, , , , - , , . - , :

%// Setup
A{1,1}=[1 2;2 4];
A{1,2}=[2 3 5;8 5 6];
A{1,3}=[7;8];
A{2,1}=[1 2;2 4]; 
A{2,2}=[1;7];

%// Make a cell array that will contain the output per row
out = cell(size(A,1),1);

for idx = 1 : size(A,1)
     %// Convert row of cell arrays to a single 2D matrix, then transpose for accumarray
      B = cell2mat(A(idx,:)).';

      %// Group IDs together and ensure they're sorted
      out{idx} = accumarray(B(:,1), B(:,2), [], @(x) {sort(x)});

      %// Add a column of IDs and concatenate with the previous output
      IDs = num2cell((1:numel(out{idx})).');
      out{idx} = [IDs out{idx}];

      %// Any cells from the grouping that are empty, eliminate
      ind = cellfun(@isempty, out{idx}(:,2));
      out{idx}(ind,:) = [];
end

:

>> out{1}

ans = 

    [1]    [         2]
    [2]    [2x1 double]
    [3]    [         5]
    [5]    [         6]
    [7]    [         8]

>> out{2}

ans = 

    [1]    [2x1 double]
    [2]    [         4]

>> celldisp(out{1}(2,:))

ans{1} =

     2

ans{2} =

     4
     8

>> celldisp(out{2}(1,:))

ans{1} =

     1

ans{2} =

     2
     7
+4

All Articles