NGXII
NGXII

Reputation: 427

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

Upvotes: 0

Views: 106

Answers (2)

YisasL
YisasL

Reputation: 335

You can get the matrix of maximum values in this way, using memory instead of high performance of processor:

a = [1 2 3];
b = [3 4 2];
c = [0 4 1];
[max_matrix, index_max] = arrayfun(@(x,y,z) max([x y z]), a,b,c);

a,b,c can be matrices also. It returns the matrix with max values and the matrix of indexes (in which matrix is found each max value).

Upvotes: 1

Steve
Steve

Reputation: 4097

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

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

Upvotes: 2

Related Questions