MATLAB: Imaginary numbers slow down code

imaginary numbersslow code

I am trying to build a complex matrix of size 1024×1024, 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

Best Answer

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.
Related Question