I have a matrix like
A= [ 1 2 4
2 3 1
3 1 2 ]
and I would like to calculate its cumulative sum by row and by column, that is, I want the result to be
B = [ 1 3 7
3 8 13
6 12 19 ]
Any ideas of how to make this in R in a fast way? (Possibly using the function cumsum)
(I have huge matrices)
Thanks!
A one-liner:
The underlying observation is that you can first compute the cumulative sums over the columns and then the cumulative sum of this matrix over the rows.
Note: When doing the rows, you have to transpose the resulting matrix.
Your example:
About performance: I have now idea how good this approach scales to big matrices. Complexity-wise, this should be close to optimal. Usually,
applyis not that bad in performance as well.Edit
Now I was getting curious – what approach is the better one? A short benchmark:
Thus: Apply outperforms matrix multiplication by a factor of 15. (Just for comparision: MATLAB needed 0.10719 seconds.) The results do not really surprise, as the
apply-version can be done in O(n^2), while the matrix multiplication will need approx. O(n^2.7) computations. Thus, all optimizations that matrix multiplication offers should be lost if n is big enough.