2

How is it possible in Matlab to join two cell arrays or structures?

I've a first cell array (or structure):

Name
A1
A1
B1
C2
C2

a second cell array (or structure):

Name  Value Type
A1     1     a
B1     56    b
C1     12    c
C2     58    c
C3     45    c
C4     15    c

I need to get this result:

Name  Value  Type
A1     1      a
A1     1      a
B1     56     b
C2     58     c
C2     58     c

Thanks

randomatlabuser
  • 626
  • 4
  • 13
TimeIsNear
  • 711
  • 4
  • 19
  • 38

1 Answers1

3

If the data are cell arrays: use the second output of ismember:

cell1 = {'A1';'A1';'B1';'C2';'C2'}; % example data
cell2 = {'A1',1;'B1',56;'C1',12;'C2',58;'C3',45;'C4',15}; % example data

[ii jj] = ismember(cell1,cell2(:,1));
result = cell2(jj(ii),:)

If the data are structure matrices: you only need small modifications to the code above:

mat1.Name = ['A1';'A1';'B1';'C2';'C2']; % example data
mat2.Name = ['A1';'B1';'C1';'C2';'C3';'C4']; % example data
mat2.Value = [1; 56;  12; 58;  45; 15]; % example data
mat2.Type = ['a';'b';'c';'c';'c';'c']; % example data

[ii jj] = ismember(mat1.Name,mat2.Name,'rows');
result.Name = deal(mat2.Name(jj(ii),:));
result.Value = deal(mat2.Value(jj(ii),:));
result.Type = deal(mat2.Type(jj(ii),:));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • @randomatlabuser Thanks! I hope my edit now doesn't make it more obscure... :-) – Luis Mendo Nov 20 '13 at 23:43
  • 1
    @LuisMendo, it's work fine, but when an item is added in cell1 I get an error. For example try with: cell1 = {'A1';'A1';'B1';'C2';'C2';'A5'}; will generate error ===> ??? Subscript indices must either be real positive integers or logicals. – TimeIsNear Nov 22 '13 at 11:54
  • 1
    I've resoved this with: result = cell2(jj(ii),:); Thanks again :) – TimeIsNear Nov 22 '13 at 11:59
  • @TimeIsNear You're right. I hadn't anticipated the case when some element of `cell1` is not present in `cell2`. I've updated my answer with your correction – Luis Mendo Nov 22 '13 at 12:34