Problem 796. Removing rows from a matrix is easy - but what about inserting rows?
Assume A is a 5-by-5 matrix. A([2,4],:) = [] is a quick way to remove rows 2 and 4. Can you find a quick way to insert rows into A?
You are given a n-by-m matrix A, a 1-by-p vector of indices IND, and either a scalar value (1-by-1) or a p-by-m matrix b to be inserted AFTER rows IND of A. In case of a scalar value it should fill the whole row. Note that IND may contain duplicate indices, which means that more than one row should be inserted after that specific row index.
For example:
A = [1 1; 3 3; 4 4]; IND = [1 3]; b = [2 2; 5 5];
should become
y = [1 1; 2 2; 3 3; 4 4; 5 5];
And
A = [0 0; 1 1]; IND = [1 1 2]; b = NaN;
should become
y = [0 0; NaN NaN; NaN NaN; 1 1; NaN NaN];
Solution Stats
Problem Comments
-
4 Comments
I corrected one error regarding isequal with NaNs, but all the other test cases are correct.
A = [1 3 5 7 9]; IND = [1 2 3 4 5]; b = [2 4 6 8 10]; definitely should result in [1 2 3 4 5 6 7 8 9 10]! You have to insert b(1) after A(1), b(2) after A(2) and so on.
Nice problem, but the specification could be improved: from the description, you'd think the entire matrix b is supposed to be inserted after each row in IND; it's only the first example that makes it clear that this is not the case.
A good problem. My first attempts at solutions used for loops and if statements, but as some of the correct submissions demonstrated, you don't need either of these to solve this problem. Vectorization is your friend.
Solution Comments
Show commentsGroup

Matrix Manipulation I
- 16 Problems
- 98 Finishers
- Remove the air bubbles
- Remove NaN ?
- N-Dimensional Array Slice
- Back to basics 21 - Matrix replicating
- Back to basics 23 - Triangular matrix
- Make an awesome ramp for a tiny motorcycle stuntman
- Flip the main diagonal of a matrix
- surrounded matrix
- Some Assembly Required
- Set some matrix elements to zero
- Matrix with different incremental runs
- Removing rows from a matrix is easy - but what about inserting rows?
- Rotate input square matrix 90 degrees CCW without rot90
- Permute diagonal and antidiagonal
- Operate on matrices of unequal, yet similar, size
- Reverse the elements of an array
Problem Recent Solvers229
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!