4
votes

I have a matrix A of size m x n and another matrix b of size 1 x n (in Matlab).

The matrix b is such that it consists of sequences of 1s, then sequences of 2s, then sequences of 3s, etc. up to some value k.

(For example b = [1 1 1 2 2 2 3 4 4], n = 9)

I want to take A, and for each row in A, choose the max in each segment, zeroing everything else in that subsequence.

So, for example, for a row A = [0 -1 2 3 4 1 3 4 5]) I would get

[0 0 2 0 4 0 3 0 5]

If there are multiple rows in A (m > 1), this should happen for each row.

I can do it easily using for loops, but it works very slowly, because I loop both over m and n.

Is there a "oneliner" to do it in Matlab, or something simple that works fast?

1

1 Answers

3
votes

If A is a single row, accumarray can do the job using an ad hoc function:

result = accumarray(b(:), A(:) ,[] , @(x) {x==max(x)});
result = vertcat(result{:}).' .* A;

Not sure how fast this will be, since it uses cells.

If A has several rows, you can use a loop over the rows.