File Exchange

image thumbnail

insertrows(A,B,ind)

version 3.00001 (4.82 KB) by

Insert rows into a matrix at specific locations

15 Downloads

Updated

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

INSERTROWS - Insert rows into a matrix at specific locations
C = INSERTROWS(A,B,IND) inserts the rows of matrix B into the matrix A at the positions IND. Row k of matrix B will be inserted after position IND(k) in the matrix A. If A is a N-by-X matrix and B is a M-by-X matrix, C will be a (N+M)-by-X matrix. IND can contain non-integers.
If B is a 1-by-N matrix, B will be inserted for each insertion position specified by IND. If IND is a single value, the whole matrix B will be inserted at that position. If B is a single value, B is expanded to a row vector. In all other cases, the number of elements in IND should be equal to the number of rows in B, and the number of columns, planes etc should be the same for both matrices A and B.
Values of IND smaller than one will cause the corresponding rows to be inserted in front of A. C = INSERTROWS(A,B) will simply append B to A.

If any of the inputs are empty, C will return A. If A is sparse, C will be sparse as well.

[C, RA, RB] = INSERTROWS(...) will return the row indices RA and RB for which C corresponds to the rows of either A and B.

Examples:
% the size of A,B, and IND all match
C = insertrows(rand(5,2),zeros(2,2),[1.5 3])
% the row vector B is inserted twice
C = insertrows(ones(4,3),1:3,[1 Inf])
% matrix B is expanded to a row vector and inserted twice (as in 2)
C = insertrows(ones(5,3),999,[2 4])
% the whole matrix B is inserted once
C = insertrows(ones(5,3),zeros(2,3),2)
% additional output arguments
[c,ra,rb] = insertrows([1:4].',99,[0 3])
c.' % -> [99 1 2 3 99 4]
c(ra).' % -> [1 2 3 4]
c(rb).' % -> [99 99]

Using permute (or transpose) INSERTROWS can easily function to insert columns, planes, etc:
% inserting columns, by using the transpose operator:
A = zeros(2,3) ; B = ones(2,4) ;
c = insertrows(A.', B.',[0 2 3 3]).' % insert columns
% inserting other dimensions, by using permute:
A = ones(4,3,3) ; B = zeros(4,3,1) ;
% set the dimension on which to operate in front
C = insertrows(permute(A,[3 1 2]), permute(B,[3 1 2]),1) ;
C = ipermute(C,[3 1 2])

See also horzcat, reshape, cat

(version 2.0, may 2008)

Comments and Ratings (23)

John

John (view profile)

Can use this to insert rows at the 0th row which is convenient. E.g.:
a=[1 3; 2 4];
b=insertrows(a,[7 7],0)

Jos (10584)

Jos (10584) (view profile)

@AAYUSH Make sure the function is on your matlab path. Check with the command "which insert rows" to ensure this.

AAYUSH

AAYUSH (view profile)

Command is good but i dont think it works with daya type "double" as i got an error saying "??? Undefined function or method 'INSERTROWS' for input arguments of type 'double'."

Chad Greene

Chad Greene (view profile)

Easy to use.

Patrik Ek

Thank you for a good function. This should be a part of MATLAB's standard package. You should consider however, the case where ind is larger than the maximum number of rows.

eg.

A = zeros(2,3) ; B = [1;1];
c = insertrows(A.', B.',5)
c =
0 0
0 0
0 0
1 1

Here it would be a good idea to add zeros at the end, or something like that. I guess the current implementation is a safety for users that have counted worng, but this should not be a limitation for the users that do this intently.

Also, the first index seems to be zero here. This is not normally the case in MATLAB and may cause confusion if a script or program have more than one author.

Frank

Frank (view profile)

Bunescu

Martin

Martin (view profile)

Jos (10584)

Jos (10584) (view profile)

@happydude: the indices in the 3r argument refer to the positions in the original array, not in the final array, as you did assume. Since the end-user is always king, I'll have to make this more clear in an update.

happydude

maybe i am running this wrong, but if I want to replace two adjact rows I seem to have problems

For example lets say I want [1, 2, 99, 99, 3, 4,]
But my original arry is [1:4]

I would have assumed you would do:
insertrows([1:4].',99,[2 3])

In face this gives the wrong answer, you would need to do:
insertrows([1:4].',99,[2 2])

This seems counterinutive? would be obliged for you help if I am missing something.

Thanks!

Dips Bhatia

Hi Jos,
Really good. Thanks

Rody Oldenhuis

Rody Oldenhuis (view profile)

I agree with John; this should be part of standard matlab. Well documented, short & simple, vectorized and ample documentation & comments; excelent.

Rubi

Rubi (view profile)

excellent file n.n thanks a lot, i had a terrible headache trying to use a for with this t=[t(1,:);[1 1];t(2:end,:)] !!

Jos (the author)

Dear Adnan Abdulally, your call "insertrows(A,AS)" is lacking a third input argument ... but anyways, it shouldn't be suprising that [A ; B] is faster than insertrows(A,B,size(A,1)).

Please need keep in mind that insertrows was not designed to simply concatenate two matrices. Let vertcat handle that!

Adnan Abdulally

Hello, i came across this program and i am seeing an increase in time vs matlabs appending function. I am looping 500 times and constantly appending AS to A, where A is originally declared as a sparse matrix of zeros size(1,n). AS is full, but is approximately 30% non-zero.

Here are the results from profiler when i have them running one after the other:

156.69s 500 66 A =insertrows(A,AS);
74.28s 500 67 B = [A;AS];

Any reason why insertrows takes longer when it claims to be faster? Am i doing something wrong to make it inefficient?

Jos (the author)

Version 2.0 incorporates the improvements and suggestions mentioned by Tim Davis.

Tim Davis

Cool! Very fast for large sparse matrices. It even keeps C sparse if A is sparse and B is full, as it should.

A few comments about the code. Why do you have the statement [abi,abi] = sort ( ... ) ? Which abi does MATLAB return? The first or 2nd argument? Looks like the 2nd. It would be more clear to write this as:

[ignore,abi] = sort ( ... ) ;
clear ignore ;

The "nargout" test is a little odd. It should read "if (nargout > 1)". Right now,
C = insertrows( ... ) is always computing RA and RB and then discarding them.

For the nargin test, I would suggest allowing C = insertrows(A,B), which just does [A;B] and returns - but optionally returning RA and RB too. It would expand B if B was a scalar, too.

Pratik Shah

Saved a lot of time. Great job!!!

Jenn Jackson

Glad I checked here first, totally saved me the time.

Scott Burnside

Helpful. Nice code. I've stopped writing these and just use this.

Jos van der Geest

If you are looking for a ND insert function, take a look at INTERLACE ("insert subarrays into array") by Duane Hanselman

Jiro Doke

Very nicely done. It is very easy to use because the syntax intuitively makes sense. Thanks.

John D'Errico

This should have been part of matlab long ago. Yes, use of [] can do this too, but this is a better solution.
Nice help, good error checking, its friendly and expands a scalar into a row. Many users will thank you for making what should be a trivial task exactly that.

Updates

3.00001

update attempt 2

3.0

updated to R2015a

MATLAB Release
MATLAB 6.5 (R13)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video