7

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 this with a for loop but with bigger matrices it will take a while. I would also like to use this to make a logical matrix in the following fashion:

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 are able to give me.

smci
  • 32,567
  • 20
  • 113
  • 146
tarikki
  • 2,166
  • 2
  • 22
  • 32

2 Answers2

9

You need to create linear indices for that. 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
carandraug
  • 12,938
  • 1
  • 26
  • 38
  • 1
    Thanks man. I was looking at sub2ind but couldn't figure it out on my own. Now I can rewrite my code snippet and ditch the loop. :) – tarikki Aug 19 '14 at 11:58
3

As per my understanding, the way to go about creating a logical matrix is below:

>A = eye(3,3)

>B = [1;3;1]

>A(B,:) =
>
>[ 1   0   0;
>  0   0   1;  
>  1   0   0; ]
Alex Myers
  • 6,196
  • 7
  • 23
  • 39
Shugeeth
  • 31
  • 2