Why do I encounter performance issues while executing FOR-loops with complex numbers?

2 views (last 30 days)
When I execute the following code:
nd =1600 ;nfc = 800;
M = repmat( diag( fft(eye(nfc)) ).',[nd 1]);
tic % Copy M into F, using a forward loop
F = zeros(nd, nfc);
for kf=1:nfc
F(:,kf) = M(:,kf);
end
toc
The output is
Elapsed time is 0.11 seconds
Now when a reverse loop is used as follows,
tic
F = zeros(nd, nfc);
% Copy M into F, reverse loop
for kf=nfc:-1:1
F(:,kf) = M(:,kf);
end
toc
the output is
Elapsed time is 12.93 seconds
which is more than 100 hundred times the timing obtained in the first case.
Indicating that, the FOR-loop execution time differs from forward loop to reverse loop.However the timings are consistent with real numbers, as shown below:
M = real(M); % transform M into real numbers
tic % Forward loop
F = zeros(nd, nfc);
for kf=1:nfc
F(:,kf) = M(:,kf);
end
toc
gives
Elapsed time is 0.06 seconds
And,
tic % Reverse loop
F = zeros(nd, nfc);
for kf=nfc:-1:1
F(:,kf) = M(:,kf);
end
toc
also gives
Elapsed time is 0.06 seconds

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This is the expected behavior, in the way MATLAB handles complex numbers. When MATLAB assigns into a complex array, it scans the array to see if the imaginary part is all zero. If this is the case, MATLAB throws away the memory used by the complex part to save memory. For example,
x = 1 + 3i;
y = 1 - 3i;
z = x + y; % the two imaginary parts cancel out and z becomes real
In the given example MATLAB scans "F" after every assignment. As soon as it sees any nonzero imaginary value in "F", it stops the scan. When filling in "F" using the forward loop, a nonzero imaginary value gets stuck into the array very early on and the scan exits early. When filling in "F" in the reverse direction, the nonzero complex values are getting stuck at the end. This causes the scan to look at almost the entire array before it finds a nonzero imaginary value. This ends up being quadratic behavior in the size of the array "F" in the worst case.

More Answers (0)

Products


Release

R14SP1

Community Treasure Hunt

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

Start Hunting!