Stuart’s MATLAB Videos

Watch and Learn

Puzzler: Intermediate sums

MATLAB challenges get thrown around the halls of The MathWorks with fair regularity. I thought this most recent one would make a good puzzler.

You have a matrix that has 3xN rows and you want to expand it such that after every third row of the original, you insert a new row which is the sum of those three rows.


a = ...
[1 2 3
1 2 3
1 2 3
3 2 1
2 1 3
1 3 2]


[1 2 3
1 2 3
1 2 3
3 6 9
3 2 1
2 1 3
1 3 2
6 6 6]

How would you do this?

For the more advanced MATLAB users, you might want to consider algorithms that use preallocation so that on larger matrices you are more memory efficient. Everyone should also think about readability of the code. I always think that a future version of me is going to look at this code, I better make it easy to understand in a week.

Please put your answers into the comments section

As always with these puzzlers, be sure to use the proper tags in the comments.

<pre> <code>
[deltaX, deltaY] = puzzler(inMatrix)
%% All the code so someone can just copy and paste it from the comments.
</code> </pre>
  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.