问题
I was wondering if there is an easy way in MATLAB to do the following operation: I'd like to copy a row or column of a matrix and insert it in the next row/column.
For example: given a 3x3 matrix
1 2 3
4 5 6
7 8 9
I'd like to copy the first row and insert it as a second row:
1 2 3
1 2 3
4 5 6
7 8 9
Can someone advise how I could accomplish this in MATLAB? Thanks!
回答1:
You can simply repeat the indices of the rows you'd like to repeat
A = A([1 1 2 3],:)
回答2:
To insert row number source as row number target:
A = [A(1:target-1,:); A(source,:); A(target:end,:)];
回答3:
A = [A(1,:); A];
回答4:
I know this is a really old topic, but this post was coming up in searches I did for the same problem when I was looking for a specific Matlab function I couldn't remember the name of--padarray.
So, you could do:
A = [1 2 3; 4 5 6; 7 8 9];
A = padarray(A,[1 0],'replicate','pre');
This is often helpful if, for example, A is the output of a function that you have not saved explicitly, so you don't know what the first row is. Anyhow, hope this helps someone!
来源:https://stackoverflow.com/questions/6246506/copy-a-row-or-column-of-a-matrix-and-insert-it-in-the-next-row-column