Accelerate nested bsxfun double loop?

20 Ansichten (letzte 30 Tage)
andrej
andrej am 7 Okt. 2013
Bearbeitet: Matt J am 8 Okt. 2013
I have a simple double loop that requires multiple 'repmat' tasks in each iteration. I'm currently using bsxfun to avoid repmats, but have found it to be only a little faster than repmat/elementwise multiplication.
Any suggestions on speeding this up?
n = 200;
U = rand(n);
M = zeros(n); % preallocate matrix
a = rand(1,n);
b = rand(1,n);
SZI = bsxfun(@times,a,b');
for j = 1 : n
j
for i = 1 : n
if i ~= j
plusvec = U(j,:).^2 - U(i,:).*U(j,:);
timesvec = U(i,:) - U(j,:);
M(i,j) = sum(sum(SZI.*(bsxfun(@plus,bsxfun(@times,U,timesvec),plusvec))));
end
end
end

Antworten (2)

Sean de Wolski
Sean de Wolski am 7 Okt. 2013
Bearbeitet: Sean de Wolski am 7 Okt. 2013
Usually two dimensional:
bsxfun(@times
Can be replaced with matrix multiplication:
SZC = b'*a;
isequal(SZC,SZI)
ans =
1
More Being a fan of "ez" speedups, I turned the outer for-loop into a parfor-loop:
With two for-loops:
timeit(@()A89455(200),0)
ans =
6.3238
With the outer loop being a parfor-loop with four local workers:
timeit(@()A89455(200),0)
ans =
3.7519
A89455 is your code in a function taking n as an input.

Matt J
Matt J am 7 Okt. 2013
Bearbeitet: Matt J am 8 Okt. 2013
Without loops:
tic;
a=a(:);
Ut=U.';
S=U*spdiags(a,0,n,n)*Ut;
S=bsxfun(@minus,diag(S).',S)*sum(b);
c=(b*U)*bsxfun(@times,Ut,a);
T=bsxfun(@minus,c(:),c);
M=S+T;
toc;
%Elapsed time is 0.002864 seconds.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by