Speed up code on GPU by removing nested for loops

Hello! I'm trying to speed up the following element-by-element array operation using the parallel computing toolbox. Is this a good candidate for arrayfun? What might that look like? Any advice would be greatly appreciated.

for ii = 1:Nx
  for jj = 1:Ny
       f1(ii,jj) = exp(i*pi*(ii + jj));
  end
end

 Akzeptierte Antwort

Bruno Luong
Bruno Luong am 1 Okt. 2018
f1 = exp((1i*pi) * (ii(:) + jj(:).'));
or on older MATLAB version (without auto expansion).
f1 = exp(bsxfun(@plus, (1i*pi) * ii(:), jj(:).'))
Avoid using ARRAYFUN with you like clear and fast code.

Weitere Antworten (3)

Noah Walcutt
Noah Walcutt am 11 Okt. 2018
Bearbeitet: Noah Walcutt am 11 Okt. 2018
Another array expansion problem, but slightly different:
for ii = 1:Nx
for jj = 1:Ny
u = delta0*(ii - Nx/2 -1);
v = delta0*(jj - Ny/2 -1);
p(ii,jj) = exp(1i*pi*lambda*z0*(u^2 + v^2));
end
end
Using bsxfun, I've got:
pp = exp(bsxfun(@plus, (1i*pi*lambda*z0*(delta0*(iii - Nx/2 -1)).^2), (jjj - Ny/2 -1).^2) );
What am I doing wrong here?
Noah Walcutt
Noah Walcutt am 11 Okt. 2018
Got it!
pp = exp(bsxfun(@plus, (1i*pi*lambda*z0*(delta0*(iii - Nx/2 -1)).^2), (1i*pi*lambda*z0*(delta0*(jjj - Ny/2 -1)).^2)));

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by