MATLAB: Simple Math With Complex Arrays

algebracomplex arraysMATLAB

I seem to be unable to do some basic arithmetic with complex numbers in matlab.
When I define the arrays,
B=complex(cos(A),sin(A));
C=complex(cos(A),sin(A));
I get complex arrays. A is real. When I then define a pair of vectors,
i=2:M-1;
j=2:N-1;
To make the following calculation,
C(i,j) = (B(i-1,j)-B(i+1,j))/(2*dx)
or this,
C(i,j)= complex(real((B(i-1,j)-B(i+1,j))/(2*dx)),imag((B(i-1,j)-B(i+1,j))/(2*dx)));
C(i,j) is real. This is just subtraction. Does there exist some way to do basic arithmetic with complex arrays? Or do I need to break these arrays up and then define my own algebra?

Best Answer

This is part of a bizarre feature that Matlab uses to save memory.
This 'bug' will always occur when an arrays values are all 0+0*i.
For instance, when troubleshooting a loop, if that loop, internally, uses complex algebra to do things like take cross products, it will look like it's malfunctioning if the initialization values in the loop are 0+0*i. It will, however, start producing complex numbers, and the complex algebra will work properly, on the second iteration if the first iteration's output is nonzero.
Related Question