Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a column/row of ones into a matrix?

Tags:

octave

Suppose that we have a 3x3 matrix like

b = 2 * eye(3); ans =  2   0   0 0   2   0 0   0   2 

and I want to a 3x4 matrix like

1   2   0   0 1   0   2   0 1   0   0   2 

What is the best way to get it?

like image 309
RubenLaguna Avatar asked Dec 02 '13 19:12

RubenLaguna


People also ask

How do you represent a column and a row in a matrix?

A matrix is denoted by [aij]mxn, where i and j represent the position of elements in the matrix, row-wise and column-wise, m is the number of rows and n is the number of columns.


2 Answers

An easy inline way to do this is:

b = [ones(size(b, 1), 1) b];

like image 131
carl_h Avatar answered Oct 19 '22 03:10

carl_h


In GNU Octave:

Concatenate two matrices together horizontally: separate the matrices by a Space,
and enclose the result in square brackets:

X = [ones(rows(X), 1) X]; 

Simpler examples:
Glue on one number (add a horizontal "Column" element with a Comma):

octave:1> [[3,4,5],8] ans =    3   4   5   8 

Glue on another matrix horizontally (as additional Columns) by using a Comma:

octave:2> [[3,4,5],[7,8,9]] ans =     3   4   5   7   8   9 

Glue on another matrix vertically (as additional Rows) by using a Semicolon:

octave:3> [[3,4,5];[7,8,9]] ans =    3   4   5    7   8   9 
like image 23
sdn342323 Avatar answered Oct 19 '22 04:10

sdn342323