Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Cell Array

Asked by Andrés

Andrés (view profile)

on 24 Apr 2012

Hello, is a simple question.

How can I remove repeated vectors from a cell array. Example:

Given a cell array {[1,2,3] [2,4] [1] [1,2,3] [5] [2,4] [1]}

I want the result:

{[1,2,3][2,4][1][5]} Thank you

0 Comments

Andrés

Andrés (view profile)

Products

No products are associated with this question.

3 Answers

Answer by Wayne King

Wayne King (view profile)

on 24 Apr 2012

One way:

   x = {[1,2,3] [2,4] [1] [1,2,3] [5] [2,4] [1]};
   y = cellfun(@num2str,x,'uniformoutput',false);
   xnew = unique(y);
   xnew = cellfun(@str2num,xnew,'uniformoutput',false);

0 Comments

Wayne King

Wayne King (view profile)

Answer by Andrei Bobrov

Andrei Bobrov (view profile)

on 24 Apr 2012
y = cellfun(@(y)[y,zeros(1,max(cellfun('size',x,2)) - numel(y))],x,'un',0);
y = cat(1,y{:});
[a,b] = unique(y,'rows','first');
[ii,ii] = sort(b);
out = x(b(ii));

EDITED

[a,n,n] = unique([x{:}])
nn = cellfun('size',x,2);
y = mat2cell(n,1,nn);
y = cellfun(@(y)[y,k*ones(1,max(nn) - numel(y))],y,'un',0);
y = cat(1,y{:});
[a,b] = unique(y,'rows','first')
[ii,ii] = sort(b);
out = x(b(ii));

2 Comments

Jan Simon

Jan Simon (view profile)

on 24 Apr 2012

Does this fail to process {[1], [1,0]}?

Andrei Bobrov

Andrei Bobrov (view profile)

on 24 Apr 2012

Hi Jan! Corrected.

Andrei Bobrov

Andrei Bobrov (view profile)

Answer by Jan Simon

Jan Simon (view profile)

on 24 Apr 2012

A dull FOR loop appraoch:

x = {[1,2,3] [2,4] [1] [1,2,3] [5] [2,4] [1]};
n = numel(x);
v = true(1, numel(x));
for i = 2:n
  tmp = x{i};
  for j = 1:i-1
    if isequal(x{j}, tmp)
      v(i) = false;
      break;  % Leave j loop
    end
  end
end
out = x(v);

0 Comments

Jan Simon

Jan Simon (view profile)

Contact us