specify rows and columns to find min value?

조회 수: 5 (최근 30일)
Andrew Poissant
Andrew Poissant 2017년 8월 10일
댓글: Stephen23 2017년 8월 10일
I have a matrix, N, and a matrix RC, and what I want is to search for a minimum value in N based on values in RC for rows and columns. Each value in RC specifies a row and col that needs to be searched in N with column 1 representing row values and column 2 representing col values. How would I go about doing this? I tried doing
[minval, minidx] = min(min(N(RC(:,1), RC(:,2))))
but it is producing incorrect results leading me to believe there is an error in my logic. rmin and cmin are 2 and 1, respectively, which is not a pair in the RC matrix.
N = [0 1 5 12 1; 1 23 4 75 5; 11 29 2 5 9; 23 3 5 8 0; 12 11 23 48 0];
RC = [1 3; 2 5; 2 3; 5 1; 2 4; 1 1; 1 5; 3 3];
[minval, minidx] = min(min(N(RC(:,1), RC(:,2))));
[rmin, cmin] = ind2sub(size(N), minidx)
  댓글 수: 3
Andrew Poissant
Andrew Poissant 2017년 8월 10일
What I expect is minval = 0 and rmin = 1, cmin = 1.
Stephen23
Stephen23 2017년 8월 10일
See my answer for a simpler and more efficient solution.

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

채택된 답변

Star Strider
Star Strider 2017년 8월 10일
This works:
N = [0 1 5 12 1; 1 23 4 75 5; 11 29 2 5 9; 23 3 5 8 0; 12 11 23 48 0];
RC = [1 3; 2 5; 2 3; 5 1; 2 4; 1 1; 1 5; 3 3];
idx = sub2ind(size(N), RC(:,1), RC(:,2)); % Define ‘Eligible’ Elements As Linear Index Vector
minval = min(N(idx)); % Minimum of ‘Eligible’ Values
minidx = find(N(:)==minval); % Location Of All Values Of ‘Eligible’ Minimum (Linear Index)
[~,minA] = ismember(idx, minidx); % Find All ‘Eligible’ Minima
[rmin,cmin] = ind2sub(size(N),intersect(minidx,idx)); % Recover Row, Column Indices Of All ‘Eligible’ Minimum
fprintf('\nMinimum of A = %d, at [%2d,%2d]\n', [minval*ones(size(rmin,1),1), rmin, cmin]')
Minimum of A = 0, at [ 1, 1]

추가 답변 (1개)

Stephen23
Stephen23 2017년 8월 10일
편집: Stephen23 2017년 8월 10일
>> N = [0,1,5,12,1;1,23,4,75,5;11,29,2,5,9;23,3,5,8,0;12,11,23,48,0];
>> RC = [1,3;2,5;2,3;5,1;2,4;1,1;1,5;3,3];
>> [val,Y] = min(N(sub2ind(size(N),RC(:,1),RC(:,2))));
>> pos = RC(Y,:)
pos = 1 1
>> val
val = 0

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by