laurajs
laurajs

Reputation: 933

Adding rows/ columns to existing matrix

I have the following matrix:

a = [16 456 22 85 93;11 78 310 62 36;1 66 23 67 405];

If I wanted to add a row would it be a = [a; randi(99, 1, 5)];? And what if I also want to add a column would it be a = [a, randi(99, 4, 1)];?

How would I add specifically between the first/second row or first/second column?

Upvotes: 0

Views: 238

Answers (2)

Adriaan
Adriaan

Reputation: 18197

a = [16 456 22 85 93;11 78 310 62 36;1 66 23 67 405]; is a 3-by-5 matrix. So if you want to add a row you need to add a 5-digit row, i.e. a = [a; randi(99, 1, 5)]; is correct. For a column it'd be a = [a, randi(99, 3, 1)];, where I replaced your 4 with a 3 to make it act on the initial matrix. Better though would be to implicitly use sizes, so that you don't have to manually increase the number of rows/columns each time:

a = [a; randi(99,1,size(a,2))]; %// adding a row
a = [a, randi(99,size(a,1),1)]; %// adding a column

If you want to insert your new row between the first and second rows:

a = [a(1,:);  randi(99,1,size(a,2)); a(2:end,:)];

Upvotes: 1

Rishit Sanmukhani
Rishit Sanmukhani

Reputation: 2269

Consider

a = [16 456 22 85 93;11 78 310 62 36;1 66 23 67 405];

To enter before ith row:

a = [ a(1:i-1,:) ; randi(99,1,5) ; a(i:end,:) ];

To enter before ith column:

a = [ a(:,1:i-1) , randi(99,4,1) , a(:,i:end) ];

Upvotes: 1

Related Questions