```Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Matix maths
Date: Thu, 15 Nov 2012 21:57:11 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 19
Message-ID: <k83ofn\$mpo\$1@newscl01ah.mathworks.com>
References: <k83i5d\$rqg\$1@newscl01ah.mathworks.com>
NNTP-Posting-Host: www-01-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1353016631 23352 172.30.248.46 (15 Nov 2012 21:57:11 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 15 Nov 2012 21:57:11 +0000 (UTC)
Xref: news.mathworks.com comp.soft-sys.matlab:782883

"Daniel Robbins" <d.w.e.robbins@gmail.com> wrote in message <k83i5d\$rqg\$1@newscl01ah.mathworks.com>...
> Does anyone know how I can sum all the diagonals of a matrix and get a vector of the results?
> For example if a had the following matrix
>
> 18    36    24    12
> 12    24    16     8
>  6    12     8     4
>
> I would get a vector of:
>
> 18  48 54 40 16 4
- - - - - - - - -
Let A be your matrix.  Then v will be your desired vector:

[m,n] = size(A);
B = [zeros(m,m-1),A,zeros(m,m-1)];
v = sum(B(bsxfun(@plus,(0:m-1:(m-1)^2)',m:m:m*(m+n-1))),1);

Roger Stafford
```