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




% Finding Max/Min Values With Multiple Occurrences
matrix = [1 2 3;
        1 23 4;
        2 23 5]
 
%Getting values
min_val = min(min(matrix));
max_val = max(max(matrix));
 
% Getting indices as vectors
% All of minx, miny, maxx, maxy are vectors
 
[minx,miny] = find(matrix==min_val);
[maxx,maxy] = find(matrix==max_val);
 
% Displaying the values
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.



Find Indices of Maximum and Minimum Value of Matrix in MATLAB

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.

Similar Reads

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....

Finding Indices of Max/Min Values in the Same Magic Square:

...

Finding Max/Min Values With Multiple Occurrences:

...