How to vectorize vector indexing?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Akzeptierte Antwort
Matt Fig
am 16 Apr. 2011
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 Kommentare
Matt Fig
am 16 Apr. 2011
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)...
Weitere Antworten (1)
Paulo Silva
am 16 Apr. 2011
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)'
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!