4

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

1
  • I've deleted my answer: read the documentation, especially the coverage of max and ind2sub. Commented Jan 3, 2013 at 13:19

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.