Effacer les filtres
Effacer les filtres

How do i refer to an entire row in a matrix, while only specifying one variable in that row?

51 vues (au cours des 30 derniers jours)
I have a matrix consisting of 2 columns and 160 rows. My aim is to automatically generate the entire row in which the second variable is the lowest of it's column. For example:
Matrix = [1 5; 4 1; 2 7; 3 8]
I need a code which generates the second row (4 1) since 1 is the lowest number in the second column. Thank you in advance for the help!

Réponse acceptée

dpb
dpb le 16 Août 2015
Modifié(e) : dpb le 16 Août 2015
Unfortunately, here's where Matlab syntax of only being able to return and use the first argument inline hurts (albeit I don't have a suggestion for an alternate syntax) so you must use an intermediate variable...
[~,ix]=min(M(:,2)); % loc of min in 2nd column
N=M(ix,:); % that row from M
This works reliably only if there is a unique minimum; if repeated minimums are possible the above will return only the location of the first of same...
  4 commentaires
Jesse Saris
Jesse Saris le 19 Août 2015
I accepted it, thank you for the advice.. I've just started working with Matlab this month. I also have a follow-up question: Is it possible to automatically delete this minimum from the matrix and continue working with the altered matrix? I now how to clear variables, but not how to delete one row out of a matrix.
Thank you again for the help!
dpb
dpb le 19 Août 2015
Set the desired row(s)/column(s) to empty ([]) ...
x(ix,:)=[]; % delete the rows in index vector ix
I suggest opening the online documentation and working thru the "Getting Started" exercises -- it'll walk you thru these kinds of introductory syntax exercises more quickly.

Connectez-vous pour commenter.

Plus de réponses (1)

matico
matico le 16 Août 2015
Something like this:
Matrix = [1 5; 4 1; 2 7; 3 8];
SecCol = Matrix(:,2);
[val,ind] = min(SecCol);
Result = Matrix(ind,:)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by