필터 지우기
필터 지우기

Efficient Way to find index of max column for each row

조회 수: 105 (최근 30일)
Varsha
Varsha 2022년 7월 12일
답변: Anay Aggarwal 2022년 7월 12일
Hey I've an matrix of size n x m. I want to find the index of max_col corresponding to each row. I know, i can use a loop to check but is there any other efficient way to do that?
thanks in advance.

답변 (4개)

Les Beckham
Les Beckham 2022년 7월 12일
편집: Les Beckham 2022년 7월 12일
Are you wanting to find the column number of the maximum value in each row? If so, this is how you can do that:
A = magic(5) % example data
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
[m, idx] = max(A, [], 2) % max value from each row and column number where the max value occurs
m = 5×1
24 23 22 21 25
idx = 5×1
2 1 5 4 3
If not, please clarify what you are trying to do.

Keshav
Keshav 2022년 7월 12일
Hi, Based on my understanding you have a matrix. for each row you want to find the index of maximum value. you can use the below code to do that.
x = [1 2 3; 5 3 4;10 8 9]
[mx,idx] = max(x,[],2)
here idx(i) will represent the index of column with max value in ith row.

Harshit Gupta
Harshit Gupta 2022년 7월 12일
Hi, I understand that you're trying to find an efficient way to find the maximum values in each row.
You can do this simply with the max() function on the matrix without using a for loop.
Here's an example:
M=[2 4 0 1;12 3 5 2;7 10 4 1;3 5 20 7]
[max_values, idx] = max(M') %row maximums
You can even get the column maximums and the maximum value of the matrix
[max_values, idx] = max(M) %col maximums
[matrix_max, idx] = max(M(:)) %matrix maximum
Hope this helps!

Anay Aggarwal
Anay Aggarwal 2022년 7월 12일
Hi Varsha,
I have an understanding that you want to find the column number of maximum element in each row of a matrix.
You can perform the following operation:
x = [1 2 3; 4 50 6;11 8 9]
x = 3×3
1 2 3 4 50 6 11 8 9
[mx,idx] = max(x,[],2)
mx = 3×1
3 50 11
idx = 3×1
3 2 1
Hope this helps
Regards

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by