Alvin Nunez
Alvin Nunez

Reputation: 247

Unique Columns Across an Array?

I have an array structured like so:

a = [1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 5 5 5 5;
     1 1 1 1 2 2 2 2 2 2 2 1 1 1 1 2 2 3 3 1 1 1 2 3 4 4 4 1 1 1 1 2 2 3 3]; 

Pretty much, it's a 2 by n (I simplified my matrix in this question with reduced number of columns for simplicity's sake), no real pattern. I want to be able to find the unique number of columns. So in this simplified example, I can (but it'll take a while) count by hand and noticed that my unique matrix b is:

b=  1 1 2 2 2 3 3 3 3 4 5 5 
    1 2 1 2 3 1 2 3 4 1 2 3

In MATLAB, I can do something like

size(b,2) 

To get the number of unique columns. In this example

size(b,2) = 12

My question is, how do I go from matrix a to matrix b so that I can do this computationally for very large n dimensional matrices that I have?

Upvotes: 2

Views: 1594

Answers (1)

sco1
sco1

Reputation: 12214

Use unique:

a = [1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 5 5 5 5;
    1 1 1 1 2 2 2 2 2 2 2 1 1 1 1 2 2 3 3 1 1 1 2 3 4 4 4 1 1 1 1 2 2 3 3];

% Transpose to leverage the rows flag, then transpose back
b = unique(a.', 'rows').';

Which returns:

b =

     1     1     2     2     2     3     3     3     3     4     5     5
     1     2     1     2     3     1     2     3     4     1     2     3

Upvotes: 2

Related Questions