Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab maximum of array with unknown dimension

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

like image 866
Breugem Avatar asked Feb 18 '23 23:02

Breugem


1 Answers

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, because ind2sub requires specifying a known number of output variables. For that purpose we can employ cell arrays and comma-separated lists, like so:

[fmax, coor] = max(A(:));
if ismatrix(A)
    C = cell(1:ndims(A));
    [C{:}] = ind2sub(size(A), coor);
    coor = cell2mat(C);
end

EDIT: I've added an additional if statement 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:

function [fmax, coor] = maxi(x)
    [fmax, coor] = max(A(:));
    if ismatrix(A)
        C = cell(1:ndims(A));
        [C{:}] = ind2sub(size(A), coor);
        coor = cell2mat(C);
    end

Example

A = [2 3; 3 4];
[fmax, coor] = maxi(A)

fmax =
    4

coor =
    2    2
like image 129
Eitan T Avatar answered Feb 27 '23 17:02

Eitan T