Selecting individual rows per column

Let's say

X = [1 2; 3 4]; c = [1 2]'; 

I would like to find a way to do what seems to me like X(:,c) . To write it as a for loop:

 for i=1:n res(i) = X(i, c(i)); end % res = [1 4] 

Is there a single statement / vectorized way to do this?

+4
source share
2 answers

diag(X(:,c)) should do the trick

Explanation: An example (a little more complex) will help to understand.

 >>X = [1 2; 3 4; 5 6; 7 8] X = 1 2 3 4 5 6 7 8 >> c = [1 1 2 1]; >> R = X(:,c) R = 1 1 2 1 3 3 4 3 5 5 6 5 7 7 8 7 

So what is going on here? For each element in vector c you select one of the columns from the original matrix X : for the first column R use the first column X For the second column R use the first column X (again). For the third column R use the second column X ... etc.

The effect of this is that the element of interest to you (defined in c ) is located on the diagonal of the matrix R Get only the diagonal using diag :

 >>diag(R) ans = 1 3 6 7 
+9
source

Use sub2ind to convert to linear indexes

 X = [1 2; 3 4]; c = [1 2]'; idx = sub2ind(size(X),1:numel(c),c(:)'); res = X(idx); 

(I used c(:)' to get c in the correct size.)

Result:

 res = 1 4 
+4
source

Source: https://habr.com/ru/post/1414553/


All Articles