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?

Keep only certain rows (with minimum values) from a matrix

Asked by Ferran

Ferran (view profile)

on 29 Jun 2013
Accepted Answer by Matt J

Matt J (view profile)

I have the following matrix:

A = [1 2; 1 3; 1 1; 2 1; 2 2; 2 0]

which has an index (1, 2, etc...) in the first column, and the relevant information in the 2nd column.

I would like to reduce this matrix so that only 1 row stays with the same index: the row with the minimum relevant value (2nd column).

It should look like this:

B = [1 1; 2 0]

the rest of the rows should not appear.

Is there an easy way I could do that?

Thank you very, very much in advance. I've been trying this for hours now and can't find an easy way to obtain B.

0 Comments

Ferran

Ferran (view profile)

Products

No products are associated with this question.

2 Answers

Answer by Matt J

Matt J (view profile)

on 29 Jun 2013
Edited by Matt J

Matt J (view profile)

on 29 Jun 2013
Accepted answer
col2=accumarray(A(:,1),A(:,2),[],@min).';
B=[1:length(col2);col2].'

1 Comment

Ferran

Ferran (view profile)

on 29 Jun 2013

Thank you very much!

Matt J

Matt J (view profile)

Answer by the cyclist

the cyclist (view profile)

on 29 Jun 2013
Edited by the cyclist

the cyclist (view profile)

on 29 Jun 2013

The unique values in the first column are

unique(A(:,1))

and the minimum values from the second column can be found using the slick accumarray() function:

accumarray(A(:,1),A(:,2),[],@min)

so you can just concatenate those

[unique(A(:,1)),accumarray(A(:,1),A(:,2),[],@min)]

to get what you want.

doc accumarray for details.

1 Comment

Ferran

Ferran (view profile)

on 29 Jun 2013

Thank you very much! It's my first time around here, so I didn't know how that "Accept answer" thing works. I ended up using both yours and Matt J's suggestions and it works great!

Thank you very much, the cyclist!

the cyclist

the cyclist (view profile)

Contact us