views:

708

answers:

2

I have a 4D array of measurements in MATLAB. Each dimension represents a different parameter for the measurement. I want to find the maximum and minimum value and the index (i.e. which parameter) of each.

What's the best way to do it? I figure I can take the max of the max of the max in each dimension, but that seems like a kludge.

A: 

might not be the most elegant solution, but you could do a quad for-loop.

for i to size
   for j to size
      for k to size
         for m to size
            if ( max < value(ijkm))
                max = value;
            else if ( min > value(ijkm))
                min = value
Andy
This is not how you do these things in Matlab.
Jonas
+12  A: 

Quick example:

%# random 4 d array with different size in each dim
A = rand([3,3,3,5]);

%# finds the max of A and its position, when A is viewed as a 1D array
[max_val, position] = max(A(:)); 

%#transform the index in the 1D view to 4 indices, given the size of A
[i,j,k,l] = ind2sub(size(A),position);

Finding the minimum is left as an exercise :).

Following a comment: If you do not know the number of dimensions of your array A and cannot therefore write the "[i,j,k,l] =" part, use this trick:

indices = cell(1,length(size(A)));

[indices{:}] = ind2sub(size(A),position);
Adrien
This is the Matlab way. If you want to find the absolute maximum, use `max(abs(A(:))` and multiply with `sign(A(position))` in case you're interested in the sign.
Jonas
Nice solution which does it in the Matlab way without any loops.
martiert
Can you get a max position indices as a vector if you don't know A's dimensions? In a function, for example.
yuk
@Adrien: Please have a look at the FAQ to see how to format your posts.
Jonas
a convenient function to solve that last comment is IND2SUBV written by *Tom Minka* as part of his Lightspeed Toolbox: http://research.microsoft.com/en-us/um/people/minka/software/lightspeed/ , you can find the function here: http://pmtk3.googlecode.com/svn/trunk/util/ind2subv.m
merv

related questions