Code covered by the BSD License

# meanDiag

### Marcus Björk (view profile)

The mean over each diagonal (or anti-diagonal) of a 2D matrix returned in a vector

meanDiag.m
```function meanVec=meanDiag(A,antiD)
%meanVec=meanDiag(A,antiD)
%The mean across each diagonal (or antidiagonal) of matrix A returned in a
%column vector. Works for 2D matrices of any size. Does not involve any
%for-loops. The first element of the returned vector is the upper right
%element (if diagonals) or upper left element (if antidiagonals), and so on.
%
%Input:
% A       -  2D Matrix
% antiD   -  Optional. Set = 1 to mean antidiagonals. Default = 0 (diagonals).
%Output:
% meanVec  -  Vector of diagonal means
%
%Written by: Marcus Bjrk, Uppsala University, 2013

[N,M]=size(A);
endFlip=0;

%Alternative to mean antidiagonals (default - diagonals)
if nargin==1
antiD=0;
end

%Make sure matrix is not wide (reduces computaional burden for very wide matrices)
if M>N
A=A.';
[N,M]=size(A);
endFlip=1;
end

Amod=zeros(N+M-1,M);
logVec = [false(M-1,1);true(N,1);false(M-1,1)];
indMat = bsxfun(@plus, (1:M+N-1)',0:M-1);
if antiD
indMat=flipud(indMat);
%indMat = bsxfun(@plus, (M+N-1:-1:1)',0:M-1);
end
logMat = logVec(indMat);
Amod(logMat)=A;

meanVec=sum(Amod,2)./sum(logMat,2); %Take the mean

%Return in correct order (compensate for wide matrix being transposed)
if endFlip
meanVec=flipud(meanVec);
end
```