Code covered by the BSD License  

Highlights from
INSERTROWS (v2.0, may 2008)

5.0

5.0 | 10 ratings Rate this file 53 Downloads (last 30 days) File Size: 2.94 KB File ID: #9984

INSERTROWS (v2.0, may 2008)

by Jos (10584)

 

14 Feb 2006 (Updated 20 May 2008)

Insert rows into a matrix at specific locations

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

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)

Acknowledgements
This submission has inspired the following:
Place one 2D matrix inside another, PWLINT: Piecewise Linear Integration
MATLAB release MATLAB 6.5 (R13)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (16)
15 Feb 2006 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.

15 Feb 2006 Jiro Doke

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

22 Feb 2006 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

27 Sep 2006 Scott Burnside

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

20 Sep 2007 Jenn Jackson

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

10 Feb 2008 Pratik Shah

Saved a lot of time. Great job!!!

18 May 2008 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.

22 May 2008 Jos (the author)

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

08 Jul 2008 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?

10 Jul 2008 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!

09 Mar 2009 Rubi

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,:)] !!

11 Aug 2009 Rody Oldenhuis

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

02 Dec 2009 Dips Bhatia

Hi Jos,
Really good. Thanks

11 Dec 2009 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!

13 Dec 2009 Jos (10584)

@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.

24 Feb 2011 Martin  
Please login to add a comment or rating.
Updates
20 May 2008

some improvements

Tag Activity for this File
Tag Applied By Date/Time
matrices Jos (10584) 22 Oct 2008 08:15:42
insert Jos (10584) 22 Oct 2008 08:15:42
reshape Jos (10584) 22 Oct 2008 08:15:42
concatenate Jos (10584) 22 Oct 2008 08:15:42
utilities Jos (10584) 22 Oct 2008 08:15:42
permute Jos (10584) 22 Oct 2008 08:15:42
rows Jos (10584) 22 Oct 2008 08:15:42
potw Cristina McIntire 07 Nov 2008 13:21:48
pick of the week Jiro Doke 11 Feb 2011 20:14:03

Contact us at files@mathworks.com