Search code examples
performancealgorithmmatlabnested-loops

Maximizing the efficiency of a simple algorithm in MATLAB


So here is what I'm trying to do in MATLAB:

I have an array of n, 2D images. I need to go through pixel by pixel, and find which picture has the brightest pixel at each point, then store the index of that image in another array at that point.

As in, if I have three pictures (n=1,2,3) and picture 2 has the brightest pixel at [1,1], then the value of max_pixels[1,1] would be 2, the index of the picture with that brightest pixel.

I know how to do this with for loops,

    %not my actual code:
    max_pixels = zeroes(x_max, y_max)
    for i:x_max
      for j:y_max
        [~ , max_pixels(i, j)] = max(pic_arr(i, j))
      end
    end

But my question is, can it be done faster with some of the special functionality in MATLAB? I have heard that MATLAB isn't too friendly when it comes to nested loops, and the functionality of : should be used wherever possible. Is there any way to get this more efficient?

-PK


Solution

  • You can use max(...) with a dimension specified to get the maximum along the 3rd dimension.

     [max_picture, indexOfMax] = max(pic_arr,[],3)