Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a vector as column-indices into rows of a matrix, 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 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.

like image 683
tarikki Avatar asked Aug 18 '14 19:08

tarikki


People also ask

How do I create a row vector in Octave?

Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. Column vectors are created by enclosing the set of elements in square brackets, using a semicolon to delimit the elements.

How do you denote columns and rows in a matrix?

A matrix with m rows and n columns is called an m × n matrix or m-by-n matrix, while m and n are called its dimensions. For example, the matrix A above is a 3 × 2 matrix. Matrices which have a single row are called row vectors, and those which have a single column are called column vectors.

How do you extract a column from a matrix in Octave?

To extract an entire row or column, use the colon : operator like this, octave#:#> X(1,:) This will extract the first row of the matrix X. In this notation, the : operator refers to all the elements in the specified row or column. To change some elements of a matrix, simply reassign their values.


2 Answers

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
like image 112
carandraug Avatar answered Sep 29 '22 19:09

carandraug


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; ]
like image 31
Shugeeth Avatar answered Sep 29 '22 19:09

Shugeeth