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 " <runraj@gmail.com> wrote in message <h61tsn$lbo$1@fred.mathworks.com>...
> 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" <b.luong@fogale.findmycountry> wrote in message <h61vj2$hqj$1@fred.mathworks.com>...
> 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!

Tags for this Thread

Everyone's Tags:

Add a New Tag:

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.

Tag Activity for This Thread
Tag Applied By Date/Time
trace array mat... Rajgopal 13 Aug, 2009 19:19:06
rssFeed for this Thread
 

MATLAB Central Terms of Use

NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Terms prior to use.

Contact us at files@mathworks.com