NGXII
NGXII

Reputation: 427

More Efficient Alternatives to Max and Min

So, I'm trying to optimize a program I made, and two glaring inefficiencies I have found with the help of the profiler are these:

    if (min(image_arr(j,i,:)) > 0.1)
      image_arr(j,i,:) = image_arr(j,i,:) - min(image_arr(j,i,:));
    end
    %"Grounds" the data, making sure the points start close to 0

Called 4990464 times, takes 58.126s total, 21.8% of total compile time.

    [max_mag , max_index] = max(image_arr(j, i, :));
    %finds the maximum value and its index in the set

Called 4990464 times, takes 50.900s total, 19.1% of total compile time.

Is there any alternative to max and min that I can use here, that would be more efficient?
There is no way to reduce the number of times these lines are called.

Upvotes: 1

Views: 703

Answers (4)

Ben Voigt
Ben Voigt

Reputation: 283624

Based on the call count, these are probably inside a loop. Both min and max are vectorized (they work on vectors of vectors).

Since you want to find extrema along the third dimension, you can use:

image_arr = bsxfun(@minus, image_arr, min(image_arr, [], 3));

and

[max_mag , max_index] = max(image_arr, [], 3);

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112659

The first part can be done without loops using bsxfun.

m = min(image_arr,[],3);
image_arr = bsxfun(@minus, image_arr, m.*(m>0.1));

Upvotes: 0

carlosdc
carlosdc

Reputation: 12132

It seems like:

   if (min(image_arr(j,i,:)) > 0.1)
      image_arr(j,i,:) = image_arr(j,i,:) - min(image_arr(j,i,:));
    end

could be rewritten like this:

data = image_arr(j,i,:);
mn = min(data);
if (mn > 0.1)
  image_arr(j,i,:) = data - mn;
end

which seems like the inner loop of something that could be written like:

minarr = min(image_arr)
[a,b] = find(minarr > 0.1);
image_arr(a,b,:) = image_arr(a,b,:) - minarr(a,b)

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283624

Rename your i and j.

Those names have meaning to MATLAB, and every time it sees them it has to check whether you have your own definition or they mean sqrt(-1).

Upvotes: 0

Related Questions