Copy the row or column of the matrix and paste it into the next row / column

I was wondering if there is an easy way in MATLAB to do the following operation: I would like to copy a row or column of a matrix and paste it into the next row / column.

For example: considering a 3x3 matrix

1 2 3 4 5 6 7 8 9 

I would like to copy the first line and paste it as the second line:

 1 2 3 1 2 3 4 5 6 7 8 9 

Can anyone advise how I can do this in MATLAB? Thanks!

+8
matrix copy matlab
source share
4 answers

You can simply repeat the indices of the rows you want to repeat

 A = A([1 1 2 3],:) 
+16
source share

Insert source line number as target line number:

 A = [A(1:target-1,:); A(source,:); A(target:end,:)]; 
+3
source share
 A = [A(1,:); A]; 
0
source share

I know this is a really old topic, but this post appeared in searches that I did for the same problem, when I looked for a specific Matlab function, I could not remember the name - padarray.

So you can do:

A = [1 2 3; 4 5 6; 7 8 9];

A = padarray (A, [1 0], 'replicate', 'pre');

This is often useful if, for example, A is the output of a function that you did not explicitly store, so you do not know what the first line is. In any case, I hope this helps someone!

0
source share

All Articles