Toike
Toike

Reputation: 147

Extract values from 2d array with indices from another array (without loops)

I have an array [2; 3] and a matrix [ 1 3 4 5; 2 4 9 2]. Now I would like to extract the second element from the first row and the third element from the second row and thus obtain [3 ; 9]. I managed it to do it with a loop, but since I'm working with much larger arrays, I would like to avoid these.

Upvotes: 1

Views: 405

Answers (2)

Thales
Thales

Reputation: 605

By exploiting the diag function, you can obtain an elegant one-line solution:

A = [1 3 4 5; 2 4 9 2];
cols = [2; 3];

B = diag(A(:,cols))
%   3
%   9

Here is what diag(A(:,cols)) does:

  1. A(:,cols) selects the columns cols of A, with column k of A(:,cols) corresponding to the column cols(k) of A, giving [3 4; 4 9];
  2. diag returns the diagonal entries of this matrix, thus returning at position k the k-th diagonal element of A(:,cols), which is A(k,cols(k)).

Upvotes: 3

Suever
Suever

Reputation: 65460

You can use sub2ind to convert each of the column subscripts (along with their row subscripts) into a linear index and then use that to index into your matrix.

A = [1 3 4 5; 2 4 9 2];
cols = [2; 3];

% Compute the linear index using sub2ind
inds = sub2ind(size(A), (1:numel(cols)).', cols);

B = A(inds)
%   3   
%   9

Alternately, you could compute the linear indices yourself which is going to be more performant than sub2ind

B = A((cols - 1) * size(A, 1) + (1:numel(cols)).');
%   3
%   9   

Upvotes: 4

Related Questions