Finding out the minimum value position of a matrix

조회 수: 4 (최근 30일)
NIRBAN CHAKRABORTY
NIRBAN CHAKRABORTY 2022년 1월 6일
댓글: Mathieu NOE 2022년 1월 6일
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

채택된 답변

Mathieu NOE
Mathieu NOE 2022년 1월 6일
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
Mathieu NOE
Mathieu NOE 2022년 1월 6일
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 2022년 1월 6일
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)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephan
Stephan 2022년 1월 6일
편집: Stephan 2022년 1월 6일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by