imaginary numbers slow down code
8 次查看(过去 30 天)
显示 更早的评论
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.
, 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 个评论
dpb
2020-3-2
Walter just means the internal runtime libraries aren't the same for real and complex; not that you have a choice.
Walter Roberson
2020-3-2
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.
采纳的回答
Steven Lord
2020-3-2
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!