I would like to compute the maximum and, more importantly, its coordinates of an N-by-N…by-N array, without specifying its dimensions.
For example, let’s take:
A = [2 3];
B = [2 3; 3 4];
The function (lets call it MAXI) should return the following values for matrix A:
[fmax, coor] = MAXI(A)
fmax =
3
coor =
2
and for matrix B:
[fmax, coor] = MAXI(B)
fmax =
4
coor=
2 2
The main problem is not to develop a code that works for one class in particular, but to develop a code that as quickly as possible works for any input (with higher dimensions).
To find the absolute maximum, you’ll have to convert your input matrix into a column vector first and find the linear index of the greatest element, and then convert it to the coordinates with
ind2sub. This can be a little bit tricky though, becauseind2subrequires specifying a known number of output variables. For that purpose we can employ cell arrays and comma-separated lists, like so:EDIT: I’ve added an additional
ifstatement that checks if the input is a matrix or a vector, and in case of the latter it returns the linear index itself as is.In a function, it looks like so:
Example