Using vector as index columns in matrix rows, in Octave
Let's say I have a matrix A and a vector B. Is it possible to use the values ββin vector B as indices to select one value from each row in matrix A? Example:
A = [1, 2, 3;
4, 5, 6;
7, 8, 9;]
B = [1;3;1]
C = A(B) or C = A(:,B)
giving:
C = [1; 6; 7]
Of course, I could do it with a for loop, but with large matrices it will take a while. I would also like to use this to make a boolean matrix like this:
A = zeros(3,3) B = [1;3;1] A(B) = 1 A = [1, 0, 0; 0, 0, 1; 1, 0, 0]
Thanks for any advice you can give me.
+3
tarikki
source
to share
1 answer
For this, you need to create linear indices. Following your example:
octave-3.8.2> a = [1 2 3
4 5 6
7 8 9];
octave-3.8.2> b = [1 3 1];
octave-3.8.2> ind = sub2ind (size (a), 1:rows (a), b);
octave-3.8.2> c = a(ind)
c =
1 6 7
+6
carandraug
source
to share