From: Stefan on
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)

% 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
From: John D'Errico on
"Stefan " <matlabgeek762(a)hotmail.com> wrote in message <i2qb20$9hc$1(a)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
From: Stefan on
you are a genius!! the profiler just told me that your way is 138 times faster than mine! this has been the bottleneck of my program, thank you so much!!!