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

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?


An easy inline way to do this is:

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


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

One way to do it is:

function [result] = prependOnes(matrix)
  result = [ones(rows(matrix),1) matrix];
end

prependOnes(b)

I Would like to point out that [A B] actually creates a new matrix as oppose to inserting, which should be obvious from its syntactic construction. But I see a lot of place use the word append or insert that I wonder whether octave does any clever thing behind, so I run a test

function testAppend(repeat)

profile off;
profile on; 
testAdd(repeat);
testAssign(repeat);
profile off;
data = profile('info');
profshow(data, 5); 

end

function testAdd(repeat)
for i = 1:repeat
    A = ones(100, 1); 
    B = ones(100, 1); 
    for j = 1:10000
        A = [A B]; 
    end 
end
end

function testAssign(repeat)
for i = 1:repeat
    B = ones(100, 1); 
    A = zeros(100, 10000);
    for j = 2:10001
        A(:, j) = B;
    end 
end
end

and here is the result

octave:1> testAppend(1)
   #              Function Attr     Time (s)        Calls
---------------------------------------------------------
   1    testAppend>testAdd             9.454            1
   3 testAppend>testAssign             0.023            1
   4                 zeros             0.001            1
   5               profile             0.000            1
   2                  ones             0.000            3

So if you need to continuously grow your matrix, create the target matrix first then assign value to it. Or implement something like resizing-matrix if you don't know the ultimate dimension in advance.


The function padarray (from the image package) was designed to do exactly that.

octave> b = 2 * eye (3)
b =

Diagonal Matrix

   2   0   0
   0   2   0
   0   0   2

octave> padarray (b, [0 1], 1, "pre")
ans =

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

The functions reads pre pad the variable b with 0 rows and 1 column. The function allows for a big flexibility when padding matrices but may be overkill for really simple stuff.