How to vectorize vector indexing?

조회 수: 9 (최근 30일)
Ken
Ken 2011년 4월 16일
I want to vectorize the operation of indexing an element in a vector. That is, given a vector of vector indices, I want to pick the corresponding elements out of a matrix where each row is the vector to index.
e.g.
For a matrix
[1 2 3 4;
5 6 7 8;
9 10 11 12]
and the vector of row indices
[2 3 1]
I want to return
[2;
7;
9]
Can this be done with a one-liner?

채택된 답변

Matt Fig
Matt Fig 2011년 4월 16일
Another approach:
% Data
A = [1 2 3 4;
5 6 7 8;
9 10 11 12];
c = [2 3 1];
%Extraction:
E = A((1:size(A,1))+(c-1)*size(A,1)).'
If size(A,1) is already known (say m=3), then the obvious simplification results...
E = A((1:m)+(c-1)*m).'
  댓글 수: 2
Ken
Ken 2011년 4월 16일
Thanks Matt and Paulo for your answers. Although the simplicity of the diag(a(:,c)) approach is the elegant solution I was looking for, it's far slower than Matt's linear indexing approach. It also exceeds MATLAB's maximum variable size much more easily because it creates a square matrix with dimension numel(c).
In a quick test indexing 50000 vectors, each 1000 elements long, the linear indexing approach was about 80 times faster than arrayfun. The diag method exceeded the maximum variable size.
Matt Fig
Matt Fig 2011년 4월 16일
Notice also that this:
ROW + (COL-1)*size(A,1)
is just an in-lining of SUB2IND for 2D matrices, something every chronic MATLABer should have memorized (IMO)...

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Paulo Silva
Paulo Silva 2011년 4월 16일
a=[1 2 3 4;
5 6 7 8;
9 10 11 12];
v=[2 3 1];
diag(a(1:end,v))
Another way
arrayfun(@(x,y)a(x,y),1:3,v)'

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by