meanDiag
by
Marcus Björk
04 Nov 2013
The mean over each diagonal (or antidiagonal) 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
%forloops. 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+M1,M);
logVec = [false(M1,1);true(N,1);false(M1,1)];
indMat = bsxfun(@plus, (1:M+N1)',0:M1);
if antiD
indMat=flipud(indMat);
%indMat = bsxfun(@plus, (M+N1:1:1)',0:M1);
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


Contact us