imaginary numbers slow down code

조회 수: 8 (최근 30일)
Isa Hendriks
Isa Hendriks 2020년 3월 2일
댓글: Walter Roberson 2020년 3월 2일
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
dpb
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
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
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
This works as of release R2016b when implicit expansion was introduced.
  댓글 수: 1
Isa Hendriks
Isa Hendriks 2020년 3월 2일
That solved my problem! Runs in an instant now, thanks so much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by