merlin2011
merlin2011

Reputation: 75545

Matlab conditional maximum without modifying vector

Suppose I have a vector of floating point numbers. Call it x.

Usually if I want the largest number in that x, I can call the matlab function max(x).

However, suppose I want the largest number, but excluding certain indices in the vector, which are specified in some other vector.

The most straightforward way to do this (and the way I would do it in C) is to loop through the vector and keep updating the max, while skipping any index that is in my second vector. That is to say, do a linear search for the maximum and skip the indices I do not want.

However, I wonder if there's a way that is more conventional in Matlab to solve this problem.

Upvotes: 1

Views: 841

Answers (2)

Shai
Shai

Reputation: 114786

Paddy's solution is Okay if you only need the max value. However, if you need the index of the maximal value as well you can no longer do

[max_m max_m_i] = max( x(include) ); 

Since the index max_m_i will be relative to the reduced array x(include) and not index into the original array x.

To circumvent this, you can use logical indexing

include = true( size(x) );
include( exclude ) = false;
[max_m max_m_i] = max( x .* include - inf .* ( ~include ) ); 

This way, we set the excluded locations to -inf so they are there (so indices are not corrupted) but they will not be selected as max.

Upvotes: 1

paddy
paddy

Reputation: 63471

Slicing your vector/matrix with a logical index is usually the way to go:

http://blogs.mathworks.com/steve/2008/01/28/logical-indexing/

Sounds like you already have your indices, so you could simply turn it around into a logical index like this:

exclude = [ ... ];
include = ones(size(x));
include(exclude) = 0;

max_m = max(x(include));

Upvotes: 2

Related Questions