Quickly applying a function to all possible combinations of vectors

3 views (last 30 days)
I have a function f that takes two vectors x and y and
f(x,y) = Transpose(sin(x-y))*Z*sin(x-y)
where Z is a diagonal positive definite matrix of appropriate size. Now, I have a matrix X where each column is a vector (so X1 = X(:,1), X2 = X(:,2), etc). I want to make a matrix K where K(1,1) = f(X1,X1), K(1,2) = f(X1,X2), etc.
I know i can do this with nested for loops but it runs very slow (X contains over 1000 points and K is calculated a few hundred times and it ends up taking about two hours). Now the code I'm basing it off of has similar functions and can do it in about 2 minutes. Anyone know how to quickly do this?
  4 Comments
Matt J
Matt J on 6 Jan 2013
Edited: Matt J on 6 Jan 2013
Yes, but will the number of rows typically be much greater, much less, or comparable to the number of columns? It would affect the approach used.
You can't perform the computation for any number of rows that you want. At some point, you're going to face limits of computer memory.
Eric
Eric on 6 Jan 2013
The number of rows will be significantly lower than the number of columns (i plan on using it for about 10 or so rows)

Sign in to comment.

Accepted Answer

Matt J
Matt J on 5 Jan 2013
Edited: Matt J on 5 Jan 2013
Using only 1 loop,
K=0;
for i=1:size(X,1)
xy=X(i,:);
K=K + sin(bsxfun(@minus,xy.',xy)).^2*Z(i,i);
end
  4 Comments
Matt J
Matt J on 6 Jan 2013
Edited: Matt J on 6 Jan 2013
The number of rows will be significantly lower than the number of columns (i plan on using it for about 10 or so rows)
When I run with size(X)=[10,2000], my proposed implementation finishes in less than 0.5 seconds. Even if you have a much poorer machine than me, there's no way it could still be taking 2 hours.
That's assuming of course that 2000 is a reasonable upper bound on the number of columns you're using. If it isn't, you might consider responding to my (third!!!) request for more full information on the size of X that you're benchmarking with.
Eric
Eric on 6 Jan 2013
Had to make some adjustments for my code and i made a mistake in translation, works great now, thanks!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!