# Thread Subject: Trace array of matrices

 Subject: Trace array of matrices From: Rajgopal Date: 13 Aug, 2009 20:43:03 Message: 1 of 4 Hi, Is it possible to vectorize the sum of the trace of an array of 2-D matrices? Currently I am doing it in a loop A = ones(4,4,N) sum = 0; for i = 1:N  sum = sum + trace(A(:,:,i)) end Any suggestions? Thanks a lot.. Purpose - speed...since N is huge!
 Subject: Trace array of matrices From: Roger Stafford Date: 13 Aug, 2009 21:00:20 Message: 2 of 4 "Rajgopal " wrote in message ... > Hi, > > Is it possible to vectorize the sum of the trace of an array of 2-D matrices? > > Currently I am doing it in a loop > > A = ones(4,4,N) > sum = 0; > for i = 1:N > sum = sum + trace(A(:,:,i)) > end > > Any suggestions? > > Thanks a lot.. > Purpose - speed...since N is huge!   You might try adding elements along the third dimension first, as in:  s = trace(sum(A,3));   By the way, never use the names of functions such as "sum" as the names of your variables. That will get matlab (and you as well) confused. Roger Stafford
 Subject: Trace array of matrices From: Bruno Luong Date: 13 Aug, 2009 21:12:02 Message: 3 of 4 One of many solutions: d=A(bsxfun(@plus,(0:size(A,3)-1)*16,(1:5:16).')); st = sum(d(:)) Bruno
 Subject: Trace array of matrices From: Rajgopal Date: 13 Aug, 2009 23:15:20 Message: 4 of 4 "Bruno Luong" wrote in message ... > One of many solutions: > > d=A(bsxfun(@plus,(0:size(A,3)-1)*16,(1:5:16).')); > st = sum(d(:)) > > Bruno Thank you so much. That speeded up my code incredibly!

### Everyone's Tags:

Separated by commas
Ex.: root locus, bode

### What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.