imaginary numbers slow down code

9 visualizaciones (últimos 30 días)
Isa Hendriks
Isa Hendriks el 2 de Mzo. de 2020
Comentada: Walter Roberson el 2 de Mzo. de 2020
I am trying to build a complex matrix of size 1024x1024, and at each index evaluate the following function: , where phi is dependent on x and y which is calculated in a seperate function called 'Phasevector2D'. aX, bX, aY and bY represent the min and max values of my x and y values.
The code below runs fine when I take small values for aX, bX, aY and bY, such as -5 to 5, but when I take bigger values (-100 to 100) the code becomes terribly slow. When phi is put equal to zero, meaning that there is no contribution from the imaginary part, the code works fine, so I am suspecting it has something to do with the imaginary number.
Does anybody underestand why this is happening? Thanks
aX = -100;
bX = 100;
aY = -100;
bY = 100;
nX = 1024;
mY = 1024;
f = complex(zeros(nX, mY));
Phasevector = zeros(nX, mY);
ii = 1;
jj = 1;
Xrange = linspace(aX, bX, nX);
Yrange = linspace(aY, bY, mY);
for x = Xrange
for y = Yrange
f(jj, ii) = exp(-pi * (x^2 + y^2) + 1i * phasevector2D(x,y));
jj = jj + 1;
end
ii = ii + 1;
jj = 1;
disp(ii);
end
The function Phasevector2D looks like below, but eventually also needs no work for x^2+y^2, x^3+y^3, sin(x+y) and similar simple functions. The output value of Phasevector2D is always smaller than 2pi.
function X = phasevector2D( x,y )
X = 50 * (x + y + 10);
X = X - fix(X/(2*pi)) * 2*pi;
end
  6 comentarios
dpb
dpb el 2 de Mzo. de 2020
Walter just means the internal runtime libraries aren't the same for real and complex; not that you have a choice.
Walter Roberson
Walter Roberson el 2 de Mzo. de 2020
dpb is exactly right. The high performance internal libraries (used for larger arrays) are specialized into real-only and complex-valued versions. The real-only versions can store more array entries at a time into primary cache, so they can be faster.

Iniciar sesión para comentar.

Respuesta aceptada

Steven Lord
Steven Lord el 2 de Mzo. de 2020
Your phasevector2D function can accept arrays of values for the x and y inputs. If you vectorize your expression for f, you don't even need the nested for loops. Hint:
x = [1 2];
y = [3; 4; 5];
z = x + y
This works as of release R2016b when implicit expansion was introduced.
  1 comentario
Isa Hendriks
Isa Hendriks el 2 de Mzo. de 2020
That solved my problem! Runs in an instant now, thanks so much!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by