Inserting Rows

Jiro's pick this week is INSERTROWS by Jos van der Geest.   This function does exactly what the name says: it inserts rows into a matrix. What makes this significant is that this seemingly trivial task is not straightforward to do in MATLAB. I can easily take rows out of a matrix, but putting rows in is not trivial. Let's say you have matrices mat1 and mat2:
mat1 = rand(5,3)
mat2 = zeros(2,3)
mat1 =
0.5626    0.6264    0.9524
0.0009    0.4245    0.8164
0.7535    0.9275    0.2145
0.9500    0.4108    0.7153
0.6666    0.5620    0.7734
mat2 =
0     0     0
0     0     0

Now, suppose you want to insert mat2 after the second row of mat2. You can use insertrows to do this:
newMat = insertrows(mat1, mat2, 2)
newMat =
0.5626    0.6264    0.9524
0.0009    0.4245    0.8164
0         0         0
0         0         0
0.7535    0.9275    0.2145
0.9500    0.4108    0.7153
0.6666    0.5620    0.7734

As an added feature, this function also allows you to insert multiple rows into different locations of the original matrix. For example, if you want to insert first row of mat2 after row 2 and the second row of mat2 after row 4:
newMAT2 = insertrows(mat1, mat2, [2 4])
newMAT2 =
0.5626    0.6264    0.9524
0.0009    0.4245    0.8164
0         0         0
0.7535    0.9275    0.2145
0.9500    0.4108    0.7153
0         0         0
0.6666    0.5620    0.7734

Also mat2 can be a single value, in which case a singleton expansion is performed:
newMAT3 = insertrows(mat1, 100, [2 4])
newMAT3 =
0.5626    0.6264    0.9524
0.0009    0.4245    0.8164
100.0000  100.0000  100.0000
0.7535    0.9275    0.2145
0.9500    0.4108    0.7153
100.0000  100.0000  100.0000
0.6666    0.5620    0.7734

Finally, I like how thorough the help and the examples are. Having good documentation greatly enhances the users' experiences, and I'm always impressed with the completeness of Jos's submissions. This function falls into one of my favorite categories - "Simple, but Useful Functions". Comments Here's a challenge for everyone. I've already asked people about their own "simple functions" in my previous blog post, but try to think about the codes that you are writing everyday, and see if you can start creating your own modular functions, regardless of how trivial they may seem. You'll find that they will make your programs much more readable and manageable. Then consider posting them to the File Exchange and let us know about your experiences here.

Published with MATLAB® 7.6
|