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

RubenLaguna picture RubenLaguna · Dec 2, 2013 · Viewed 65.5k times · Source

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?

Answer

carl_h picture carl_h · Dec 2, 2013

An easy inline way to do this is:

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