Remy
Remy

Reputation: 97

How to efficiently find maximum of selected indices of an array in MATLAB?

Let us say we have the vectors: w, s_on, and s_off. s_on and s_off have the ascending indices of the onset and offset of an event. We need to find the maximum value in during each event. How can we do it without using loop. for example we may have the following values:

s_on = [5 19 78 101];
s_off = [10 28 97 152];
w = rand(1,200);

The following code does not work:

pv = max(w(s_on(1:end):s_off(1:end)))

Upvotes: 1

Views: 35

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Let the data be defined as

s_on = [5 19 78 101];
s_off = [10 28 97 152];
w = rand(1,200);

The maximum for each range of indices can be computed as follows:

[v, t] = max(bsxfun(@ge, 1:numel(w), s_on(:)) & bsxfun(@le, 1:numel(w), s_off(:)), [], 1);
result = accumarray(t(v).', w(v).', [], @max);

A loop would be more readable:

result_loop = NaN(numel(s_on), 1);
for k = 1:numel(s_on)
    result_loop(k) = max(w(s_on(k):s_off(k)));
end

Check that both approaches give the same result:

isequal(result, result_loop)

Upvotes: 1

Related Questions