1
votes

I'm working on a piece of software in MATLAB and I believe I've reached the limit of my knowledge when it comes to optimisation and efficiency. Here's where the expertise of the people on StackOverflow might be helpful.

Using MATLAB's profiler, I've found that the last inefficient line of code is a multiplication of the following form:

function [energy] = getEnergy(S,W)
  energy = -(S*W*S');
end

S is a 1xN row vector, W is an NxN matrix (it's not just a diagonal matrix though), and S' is a Nx1 column vector, whose multiplication returns a number.

I understand that this is a primitive operation, but I was wondering whether there is any way to speed this up.

I tried searching Google etc, but unfortunately I do not know the right keywords to search for. I apologise if this is a duplicate.

Thanks in advance.

2
your profile's picture is a bit offensive. would you consider replacing it with something less disturbing? - Shai
@sudosensei Are there any special attributes to matrix W? For example, is it symmetric? - Eitan T
Matlab is quite efficient when it comes to matrix/vector products. Use profiler to spot your bottleneck more carefully. - Shai
@EitanT: Yes, actually W is symmetric. - sudosensei
That's exactly the line of code MATLAB's profiler highlights. - sudosensei

2 Answers

0
votes

Your implementation is correct, and the fastest.

You can save ~20-30% of computation time by performing it inside the main code, without call to the function.

>> S = randn(1, 500);
>> W = randn(500);
>> tic; for k = 1 : 10000, e = -(S * W * S'); end; toc
Elapsed time is 0.321595 seconds.
0
votes

If the bottleneck stems from the fact that you need to repeat this computation for a LOT of different vectors S, then you can do the following vectorization:

% s is k-by-N matrix of k row vectors
energy = sum( ( s * W ) .* s, 2 ); % note the .* in the middle!