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

Thread Subject:
unique() Help

Subject: unique() Help

From: Husam Aldahiyat

Date: 7 Sep, 2009 15:58:02

Message: 1 of 5

Hello,
I need a function that outputs the unique elements of each column of my desired matrix.
I can use
sum(~~diff(sort(A)))+1
to get the number of unique elements in each column of a matrix A,
but can't I produce a cell or zero padded matrix for what the unique elements are?
I used a loop and it takes 99% of my calculation time and is killing me!

Help!!!

Subject: unique() Help

From: dpb

Date: 7 Sep, 2009 16:06:41

Message: 2 of 5

Husam Aldahiyat wrote:
> I need a function that outputs the unique elements of each column of my desired matrix.
...

How about (for matrix x)

for i=1:size(x,2), u{i} = unique(x(:,i)); end

--

Subject: unique() Help

From: arun

Date: 7 Sep, 2009 16:16:40

Message: 3 of 5

On Sep 7, 5:58 pm, "Husam Aldahiyat" <numand...@gmail.com> wrote:
> Hello,
> I need a function that outputs the unique elements of each column of my desired matrix.
> I can use
> sum(~~diff(sort(A)))+1
> to get the number of unique elements in each column of a matrix A,
> but can't I produce a cell or zero padded matrix for what the unique elements are?
> I used a loop and it takes 99% of my calculation time and is killing me!
>
> Help!!!

given matrix y (with n columns),
u = arrayfun(@(x) unique(y(:,x)), 1:size(y,2), 'uni', false);
will give a 1*n cell array with each element holding the unique
elements of the column.
best, arun.

Subject: unique() Help

From: Husam Aldahiyat

Date: 7 Sep, 2009 16:44:02

Message: 4 of 5

dpb, thanks for the effort but I already said no loops.

arun, thanks alot!!!!!!!!!!!!! :)

Subject: unique() Help

From: Matt Fig

Date: 8 Sep, 2009 03:43:05

Message: 5 of 5

With a little prep work, the arrayfun solution can be made faster:

%%%
t = sort(y);
d = [true(1,size(y,2)); 0~=(diff(t))]; % Replace call to unique with index into t.
U = arrayfun(@(x) t(d(:,x),x),1:size(y,2),'Un',0); % Slow because of anon. func.
%%%


But this is still NOT as fast as the For loop:

%%%
t = sort(y);
d = [true(1,size(y,2)); 0~=(diff(t))];
U2 = cell(1,size(y,2));

for ii = 1:size(y,2)
    U2{ii} = t(d(:,ii),ii); % Replace call to unique with index into t.
end
%%%


For a random array 30-by-2000, the For loop is 4 times faster than the above arrayfun, and 15 times faster than the one line arrayfun approach, at least using 2007b.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us