slayton
slayton

Reputation: 20319

Selecting entries from a matrix without using a loop

I have two matrices A and B, both of which are Nx3 matrices.

I'm currently getting the maximum value and index for each row of matrix A using:

[maxA, idx] = max(A, [], 2)

idx(j) indicates which column contained the maximum for row j. Now I'd like to select those same positions from matrix B.

I've currently implemented this using a loop:

for j = 1:numel(idx)
   maxB(j) = B(j, idx(j))
end

My current implementation is fast enough, although I prefer to avoid unneeded loops so is there a way to express this without a loop?

Upvotes: 1

Views: 143

Answers (3)

Serg
Serg

Reputation: 14098

In one line:

maxB = B(A == max(A, [], 2) * ones(1, 3));

But this is not safe. It assumes unique values in every row of A.

Upvotes: 0

mwengler
mwengler

Reputation: 2778

You can construct the single dimension index into the matrix and get them that way. All multidimensional matrices in matlab can be addressed.

You can use

maxB = B(sub2ind([1:length(idx)]',idx(:)));

Upvotes: 2

O. Th. B.
O. Th. B.

Reputation: 1353

You can build a vector of linear indices (I expect B to be the same size as A):

vec_indices = sub2ind(size(A), 1:numel(idx), idx);

Then you can use that vector directly for lookup:

maxB = B(vec_indices)

Upvotes: 2

Related Questions