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?

How can I get a row vector where a specific element found is located within a matrix?

Asked by Erika

Erika

on 10 Oct 2012
Accepted Answer by Andrei Bobrov

Andrei Bobrov

I am trying to write a program that gives a row vector from a matrix that has the lowest element from a specific column. For example, say if I have the following,

A =

2009 8 2 4

2010 3 4 5

2011 6 9 1

2012 1 3 7

If I want to find the smallest value in column 3, which is 2, how do I get MATLAB to give the row where it is found, so that the result is

ans =

2009 8 2 4

I have been struggling with this for the past 2 days and I feel like because I've stared at this for so long I can't spot the problem. Can I get some help please?

0 Comments

Erika

Erika

Products

No products are associated with this question.

2 Answers

Answer by Andrei Bobrov

Andrei Bobrov

on 10 Oct 2012
Edited by Andrei Bobrov

Andrei Bobrov

on 10 Oct 2012
Accepted answer
A =[
2009 8 2 4
2010 3 4 5
2011 6 9 1
2012 1 3 7];
[ii,ii] = min(A(:,3));
out = A(ii,:);

or

out = A(abs(A(:,3) - min(A(:,3))) < eps(100),:);

0 Comments

Andrei Bobrov

Andrei Bobrov

Answer by Erika

Erika

on 10 Oct 2012

Thank you! I do have a question, however. Why are you using ii twice? What does this do that allows to get the row vector where a specific element found is located within a matrix? I ask this so that I know next time.

3 Comments

Matt Tearle

Matt Tearle

on 10 Oct 2012

That's just an old trick for ignoring the first output from min -- you don't actually need the minimum value, just its location. But MATLAB assigns multiple function outputs by order; for min the first output is the minimum value, the second is its location. If you're using any recent version of MATLAB, a neater(?) solution is

[~,ii] = min(A(:,3));
out = A(ii,:);

BTW, is it possible that you would have multiple locations with the same minimum value? If so, how do you want to deal with it? Andrei's answer will give the first row that matches. If you need all rows that match:

idx = A(:,3)==min(A(:,3));
out = A(idx,:);

(Of course, both are equivalent if there's only one minimum.)

Andrei Bobrov

Andrei Bobrov

on 10 Oct 2012

Hi Matt! Second part in my answer?(after 'or')

Matt Tearle

Matt Tearle

on 15 Oct 2012

Oh, yes, you're right -- I was a bit confused by the eps and didn't look too closely.

Erika

Erika

Contact us