1) Assigning a complex value to a real vector requires MATLAB to convert the real vector to a complex vector, which can take a while for large vectors.
2) Assigning a real or complex value to a complex vector requires MATLAB to check whether the imaginary part of the complex vector is all 0's or not. If the complex vector's imaginary part is all 0's, MATLAB has to convert the complex vector to a real vector. This will take longer depending on how long it takes to find any nonzero imaginary parts in the complex vector.
Workaround
In the example provided, the operations can be sped up by initializing the `result` vector to be all 1i values. This works because, after the first loop, `result` remains complex throughout the rest of the script (so no further conversions between real/complex vectors are needed). This also increases the number of non-zero imaginary components in `result` thereby increasing the speed with which MATLAB can detect that `result` does not need to be converted into a real vector.
Note that this would not yield the same result if our script did not rewrite all of the `result` vector (since we would have 1i values at the locations we did not overwrite).
e.g.
% my_script.m
...
result = repmat(1i,300000000,1);
...
--------------------------------------------------------
>> my_script
assign real values to a real vector
Elapsed time is 0.000161 seconds.
Elapsed time is 0.000028 seconds.
Elapsed time is 0.000024 seconds.
Elapsed time is 0.000022 seconds.
Elapsed time is 0.000216 seconds.
assign a complex value to a real vector
Elapsed time is 0.000599 seconds.
assign real values to a complex vector
Elapsed time is 0.000032 seconds.
Elapsed time is 0.000023 seconds.
Elapsed time is 0.000022 seconds.
Elapsed time is 0.000022 seconds.
Elapsed time is 0.000182 seconds.
assign complex values to a complex vector
Elapsed time is 0.000102 seconds.
Elapsed time is 0.000070 seconds.
Elapsed time is 0.000067 seconds.
Elapsed time is 0.000066 seconds.
Elapsed time is 0.000740 seconds.
NOTE: The same reasoning applies when dealing with large real/complex matrices, etc.
Best Answer