c=complex(a,b)
in matlab is much slower than doing c=a+1i*b
.
The following is in Matlab 2018a
a=rand(15000);
b=rand(15000);
%
clear c;
tic; c=a+1i*b; toc
Elapsed time is 0.338525 seconds
%
clear c;
tic; c=complex(a,b); toc
Elapsed time is 2.542403 seconds.
Is the complex
actually useful in any situation? Why is it so slow?
I wanted to add some historical perspective:
In versions of MATLAB prior to R2018a, complex numbers were stored in separate real and imaginary arrays internally. Thus, the result of complex
could just point at the data for the two input arrays. complex(a,b)
was thus very fast and memory-efficient compared to a+1i*b
which actually needs to do arithmetic and create new memory storage.
In the current version of MATLAB, complex data is stored in “interleaved format”, meaning it’s a single array with real and complex values for each array element next to each other. This means data needs to be copied with either format, complex
has lost its value.
The documentation and the command-line help give some hints as to when it may be useful: when you want to force a complex-type result even if the imaginary part is zero, or when you have integer data types as inputs:
C = COMPLEX(A,B)
returns the complex resultA + Bi
In the event that
B
is all zeros,C
is complex with all zero imaginary part, unlike the result of the additionA+0i
, which returns a strictly real result.The
complex
function provides a useful substitute for expressions such asA+1i*B
orA+1j*B
in cases whenA
andB
are not single or double, or whenB
is all zero.
As for why it is slower: we can only guess, because it's a built-in function; but checking if the inputs are not floating point or if the second input is all zeros may account for some of the extra time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With