A fairly general solution:
[ sum(~sum(m(:,[]),2)) sum(~sum(m([],:),1)) ]
It accepts empty matrices (with 0 columns, 0 rows or both), as well as complex , NaN or inf .
It is also very fast : it takes about 22 microseconds for a 1000 Γ 1000 matrix on my old laptop (a for loop with 1e5 repetitions takes 2.2 seconds, measured with tic , toc ).
How it works:
Keys to handling empty matrices in a unified way:
- empty indexing (that is, indexing with
[] ); - the fact that summing over an empty dimension yields zeros.
Let r and c be (possibly zero) numbers of rows and columns m . m(:,[]) is an empty vector r Γ 0. This is true even if r or c are zero. In addition, this empty indexing automatically provides insensitivity to NaN , inf or complex values ββin m (and probably also takes into account the short calculation time).
Summing this vector r Γ 0 by its second size ( sum(m(:,[]),2) ), a vector of r Γ 1 zeros is output. Denial and summation of this vector gives r.
The same procedure is applied to the number of columns, c, by empty indexing in the first dimension and summing over this dimension.
source share