MATLAB: Is assigning integers to a complex matrix slow

MATLAB

I have created a complex matrix. When I change a value to a non-zero element, I can see a drastic decrease in performance which does not occur if I set the value to the original one.

Best Answer

The difference in performance you observe is a side effect of MATLAB's feature to diligently inspects its complex variables to determine whether they are truely complex (with at least one non-zero imaginary element) or otherwise it will throw away their imaginary part.
MATLAB does this inspection after every modification of the complex variable. The inspection of the imaginary part is a linear scan: scan the imaginary part from the first to the last element until it finds the first non-zero imaginary part. Thus the earlier (closer to the beginning) the first non-zero imaginary part occurs, the less time MATLAB spends on this inspection. The worst case is when all elements have zeros imaginary part except for the last element. In this case, MATLAB has to scan the entire array to determine it is indeed complex, and keeps its imaginary part. 
There are several workarounds to speed up the assignment to complex variables:
1. Assign real and complex parts of numbers as two real matrices. Note that this will lead to code that is more complex and harder to maintain, and is not recommended unless absolutely necessary.
2. Initialize complex matrices so that the first element contains the entry '0 + 1*i'. Then, traverse through the matrix backwards when assigning, as shown below:
d = zeros(1e6,20,'single');
v = zeros(1e6,1, 'single');
d(1) = 0+i;
for k = 20:-1:1
d(:,k) = v;
end
3. Explicitly assign complex matrices using the form 'a+i*b', as shown below:
d = zeros(1e6,20,'single') + i*zeros(1e6,20,'single');
v = ones(1e6,1,'single');
for k = 1:20
d(:,k) = v + i.*v;
end