Quantcast
Channel: MATLAB Central Newsreader - tag:"optimization"
Viewing all articles
Browse latest Browse all 130

Re: only need diagonal elements of huge matrix

$
0
0
"John D'Errico" wrote in message <i2qft4$dh0$1@fred.mathworks.com>...
> "Stefan " <matlabgeek762@hotmail.com> wrote in message <i2qb20$9hc$1@fred.mathworks.com>...
> > I have an optimization problem, hopefully someone can help me.
> >
> > T is an Mxn matrix
> > H is an nxn matrix
> > (M is huge (>500), n is 25 at max)
>
> 500 is simply NOT huge by any measure.
>
>
> >
> > % my way 1:
> > E=nan(M,1);
> > for k=1:M
> > t = T(k,:);
> > E(k) = t * H * t' ;
> > end
> >
> > % my way 2:
> > whatever = T * H * T' ;
> > E = diag(whatever);
> >
> >
> > Although way 2 is faster (really, I could not believe it myself!) it still takes up most of the calculation time of my program (and this is only a very small part of it). Since it calculates a 500x500 matrix and then discards everything except the main diagonal I was hoping there is a way to just calculate what I need without using a loop
> >
> > any help is appreciated .. thanks in advance
>
> This will do it, and require less time in theory, since
> it does not compute the off-diagonal elements.
>
> E = sum((T*H).*T',2);
>
> Compare the time required though, for a simple
> test case.
>
> T = rand(500,25);
> H = rand(25,25);
>
> tic,E0 = diag(T*H*T');toc
> Elapsed time is 0.004898 seconds.
>
> tic,E1 = sum((T*H).*T,2);toc
> Elapsed time is 0.003793 seconds.
>
> Verify that the two expressions yield the same result.
>
> std(E0 - E1)
> ans =
> 0
>
> Yes, the latter method is faster. But this is simply not
> a big problem,and certainly not huge in the scheme
> of things.
>
> John

John,

First, I'm happy to find this old thread. Just wanted to point out a typo in your response:

> E = sum((T*H).*T',2);

should be

E = sum((T*H).*T,2);

i.e., without the transpose on the second T.

Best,

Cliff

Viewing all articles
Browse latest Browse all 130

Trending Articles