Find Indices of Maximum and Minimum Value of Matrix in MATLAB
Last Updated :
21 Nov, 2022
Matrices in MATLAB are 2-dimensional arrays that store mostly numeric data at different indices. Now, to find the indices of maximum and minimum values of a given matrix, MATLAB does not provide any direct functionality however, we can do the same by using two other functionalities. Firstly, we will find the maximum or minimum value of a given matrix and then, we will find the indices of those two values. In this scenario, MATLAB does offer simple functions to perform the former tasks. In this article, we shall see how to do the same for a magic square.
Maximum and Minimum Values in a Matrix:
The max() and min() functions find the maximum and minimum values respectively in an array, along a given dimension. The output of these commands will be a row vector(default) which will have max/min values of each column in that array/matrix. Then we can apply the max()/min() function again to find the max/min values from that 1D vector.
Syntax:
To get row vectors with extreme values
max-row = max(matrix)
min-row = min(matrix)
To get extreme value from a given row vector of extreme values
max(max-row)
min(min-row)
Now let us see the same in action.
Maximum Value:
We will create a 5×5 magic square and find its maximum value, which should be 25.
Example 1:
Matlab
matrix = magic(5)
max_val = max(max(matrix))
|
Output:
Minimum Value:
Similarly, we will now find the minimum value of the same magic square, which should be 1.
Example 2:
Matlab
matrix = magic(5)
min_val = min(min(matrix))
|
Output:
Finding Indices of Max/Min Values in the Same Magic Square:
Now we will use the find() function to get the indices of the max/min values.
Syntax:
max-index = find(matrix==max_val)
min-index = find(matrix==min_val)
Example 3:
Matlab
matrix = magic(5);
min_val = min(min(matrix));
max_val = max(max(matrix));
[minx,miny] = find(matrix==min_val);
[maxx,maxy] = find(matrix==max_val);
fprintf( "minimum index" )
disp([minx,miny])
fprintf( "maximum index" )
disp([maxx,maxy])
|
Output:
Finding Max/Min Values With Multiple Occurrences:
We can also find the indices of all occurrences of the max/min value of a matrix in a similar way. See the following code for understanding the same.
Example 4:
Matlab
matrix = [1 2 3;
1 23 4;
2 23 5]
min_val = min(min(matrix));
max_val = max(max(matrix));
[minx,miny] = find(matrix==min_val);
[maxx,maxy] = find(matrix==max_val);
fprintf( "minimum index\n" )
disp([minx,miny])
fprintf( "maximum index\n" )
disp([maxx,maxy])
|
Output:
As can be seen, the minimum value 1 occurs at (1,1) and (2,1), and the maximum value 23 occurs at (2,2) and (3,2) indices. The same results are given by the above code.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...