Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Matix maths

1 view
Skip to first unread message

Daniel Robbins

unread,
Nov 15, 2012, 3:09:17 PM11/15/12
to
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

All help appreciated!
Dan

dpb

unread,
Nov 15, 2012, 3:25:13 PM11/15/12
to
On 11/15/2012 2:09 PM, Daniel Robbins wrote:
> 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
>

Not terribly clever, but...given your array as 'm'--

>> n=fliplr(m)
n =
12 24 36 18
8 16 24 12
4 8 12 6
>> [nr,nc]=size(n);d=nc-1;for i=1:nr+nc-1,sum(diag(n,d)),d=d-1;end
ans =
18
ans =
48
ans =
54
ans =
40
ans =
16
ans =
4
>>

--



Nasser M. Abbasi

unread,
Nov 15, 2012, 3:35:50 PM11/15/12
to
On 11/15/2012 2:09 PM, Daniel Robbins wrote:
completley not clear question. Which diagonals? positive slope or
negative slope? which sub matrices are you summing its diagonals?

I can see where the '18' and the '48' and the '54' came from. But
the rest is not clear now how you got it.





Roger Stafford

unread,
Nov 15, 2012, 4:57:11 PM11/15/12
to
"Daniel Robbins" <d.w.e....@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

Bruno Luong

unread,
Nov 15, 2012, 5:49:21 PM11/15/12
to
A=[18 36 24 12
12 24 16 8
6 12 8 4]

[m n]=size(A);
[I J]=ndgrid(1:m,1:n);
accumarray(I(:)+J(:)-1,A(:))

% Bruno

Bruno Luong

unread,
Nov 15, 2012, 5:59:16 PM11/15/12
to
[m n]=size(A);
K=hankel(1:m,m+(0:n-1))
accumarray(K(:),A(:))

% Bruno

Daniel Robbins

unread,
Nov 16, 2012, 4:50:10 AM11/16/12
to
Thanks to everyone who gave solutions, good to have a range of options to pick from!!
0 new messages