Finding out the minimum value position of a matrix

3 vues (au cours des 30 derniers jours)
NIRBAN CHAKRABORTY
NIRBAN CHAKRABORTY le 6 Jan 2022
Commenté : Mathieu NOE le 6 Jan 2022
I have a matrix (a=[1 2 3 4 5 10;2 3 5 6 1 12;2 6 4 5 7 16;10 2 1 4 5 20;2 3 1 4 9 12])
I want to find out the minimum value postion in 2nd row from 1st to 3rd column
I have written this code
[r1,c1]=find(a(i,1:6)==min(a(i,4:6)))
But insted of showing the position as 2nd row 1st column it is showing like this
i1 =
1
j1 =
1
can you please help me where i have done the mistake

Réponse acceptée

Mathieu NOE
Mathieu NOE le 6 Jan 2022
hello
try this
your answer is in r_final and c_final
a=[1 2 3 4 5 10;2 3 5 6 1 12;2 6 4 5 7 16;10 2 1 4 5 20;2 3 1 4 9 12]
rr = 2;
cc = (1:3);
[r,c] = find(min(a(rr,cc)));% r and c referenced to rr and cc
r_final = rr(r);
c_final = cc(c);
  3 commentaires
Mathieu NOE
Mathieu NOE le 6 Jan 2022
My bad
find is anyway not needed here - forgot that
this is a better code - tested here with your inputs
r_final = 5
c_final = 3
a=[1 2 3 4 5 10;2 3 5 6 1 12;2 6 4 5 7 16;10 2 1 4 5 20;2 3 1 4 9 12]
rr = 5;
cc = (1:3);
b = a(rr,cc);
[value, index] = min(b(:));
[r,c] = ind2sub(size(b), index);% r and c referenced to rr and cc
r_final = rr(r);
c_final = cc(c);
Mathieu NOE
Mathieu NOE le 6 Jan 2022
NB this code works also with multiple rows and multiple cols
a=[1 2 3 4 5 10;2 3 5 6 1 12;2 6 4 5 7 16;10 2 2 4 5 20;2 3 1 4 9 12]
rr = (4:5);
cc = (1:3);
b = a(rr,cc);
[value, index] = min(b(:));
[r,c] = ind2sub(size(b), index);% r and c referenced to rr and cc
r_final = rr(r)
c_final = cc(c)

Connectez-vous pour commenter.

Plus de réponses (1)

Stephan
Stephan le 6 Jan 2022
Modifié(e) : Stephan le 6 Jan 2022
a=[1 2 3 4 5 10;2 3 5 6 1 12;2 6 4 5 7 16;10 2 1 4 5 20;2 3 1 4 9 12]
a = 5×6
1 2 3 4 5 10 2 3 5 6 1 12 2 6 4 5 7 16 10 2 1 4 5 20 2 3 1 4 9 12
% Here for the example row = 5, col = 1...3
ii = 5; % wanted row
range = 1:3; % column range
[r,c] = find(a==(min(a(ii,range)))); % all values that are equal the min of row 2, col 1:3
pos = [r(r==ii), c(r==ii)] % the correct position for the wanted row
pos = 1×2
5 3

Catégories

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

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by