How to find the min values and their indices for a 2D array?

조회 수: 157 (최근 30일)
ilyes louahem m'sabah
ilyes louahem m'sabah 2023년 9월 11일
댓글: Adam Danz 2023년 9월 12일
I have the following 10x5 array: LLP
I want to get the min value of this array and all its induces. I mean (4,5), (5,1), (5,2)....and so on

채택된 답변

Adam Danz
Adam Danz 2023년 9월 11일
편집: Adam Danz 2023년 9월 11일
Find the minimum value using min and specify all dimensions. Then use find with two outputs to find the row and column indices of the matrix that equal the minimum value.
% demo data
m = [3 0 1 0 2; 2 2 0 0 3]
m = 2×5
3 0 1 0 2 2 2 0 0 3
minval = min(m,[],'all');
[row, col] = find(m == minval)
row = 4×1
1 2 1 2
col = 4×1
2 3 4 4
Common pitfalls
min() has a second output that returns the indicies of the min value but, by default, it will return the row index of the first matching minimum value for each column.
[minval, idx] = min(m)
minval = 1×5
2 0 0 0 2
idx = 1×5
2 1 2 1 1
You can specify the linear option to return the linear index rather than a row index but this will still return the first matching minimum for each column, not all matches of the global minimum.
[minval, idx] = min(m,[],'linear')
minval = 1×5
2 0 0 0 2
idx = 1×5
2 3 6 7 9
If you specify all dimensions, it will return the first match of the minimum value, with or without the linear option.
[minval, idx] = min(m,[],'all')
minval = 0
idx = 3
  댓글 수: 5
ilyes louahem m'sabah
ilyes louahem m'sabah 2023년 9월 12일
now i have another matrix called f with the same dimension of m. I want to find the min of the values of f corresponding to the indices found in m. I mean the indices row and col .
I want something like this: min(f(row,col))
Adam Danz
Adam Danz 2023년 9월 12일
Convert the (row, col) subscript indices to a linear index using sub2ind. Demo:
m = [3 0 1 0 2; 2 2 0 0 3]
m = 2×5
3 0 1 0 2 2 2 0 0 3
minval = min(m,[],'all');
[row, col] = find(m == minval)
row = 4×1
1 2 1 2
col = 4×1
2 3 4 4
f = rand(size(m))
f = 2×5
0.0784 0.5513 0.4124 0.9789 0.3237 0.6348 0.8458 0.7896 0.7465 0.1948
ind = sub2ind(size(m),row,col);
f(ind)
ans = 4×1
0.5513 0.7896 0.9789 0.7465

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by