Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of Matlab's "complex" function?

Tags:

matlab

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?

like image 552
avgn Avatar asked Dec 17 '22 21:12

avgn


2 Answers

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.

like image 87
Cris Luengo Avatar answered Dec 31 '22 17:12

Cris Luengo


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 result A + Bi

In the event that B is all zeros, C is complex with all zero imaginary part, unlike the result of the addition A+0i, which returns a strictly real result.

The complex function provides a useful substitute for expressions such as A+1i*B or A+1j*B in cases when A and B are not single or double, or when B 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.

like image 38
Luis Mendo Avatar answered Dec 31 '22 18:12

Luis Mendo