MATLAB: Complex plots bug

complex plots bugMATLAB

Am I doing something wrong or is this a bug in Matlab plotting?
Set up nested for loops to iterate through the real and complex values in the complex plane and evaluate a function on the complex domain for some criteria. Use real(z^2) > 0 as an example. Plot any z values that meet the real(z^2) > 0 criteria.
The resulting plots have the following 2 bugs: a phantom vertical line at Real value 1 and no points plot along the real axis. Command line testing of the evaluation shows that matlab is correctly executing the function and reporting the correct values, so it seems to be something in the handoff to the plot engine (maybe??). Is there some known way to work around this?
Example code:
%------------------------------------------------------------------------------------------------------------------------------------------------------------------
clf
hold on
grid on
xlim([-5 5])
ylim([-5,5])
disp("starting job...")
for zx=-5:.1:5
for zy=-5:.1:5
z=zx+zy*i; %compose z from real and imag parts
if(real(z^2)>0) %sample function evaluation criteria
plot(z,'b.') % bug has plots showing a vertical line at re(1) and no points on the real axis.
end
end
end
disp("job complete")
sample output:

Best Answer

"Am I doing something wrong or is this a bug in Matlab plotting?"
There is no bug in the plotting.
Exactly as documented, when z is complex, plot will plot the imaginary part against the real part.
What you have overlooked is that MATLAB silently removes the "complex" property from an operation's output array when the imaginary part of every value in that array is zero. And that is what happens with some of your values, the ones where you multiply i by zero... which not surprisingly have zero imaginary part, therefore z is not a complex array, and so the input to plot is not a complex array, so plot applies other rules (plotting the input value against the indices of that input array, which for a scalar are always 1).
You can check this yourself by only plotting the non-complex values inside your loop:
if isreal(z)
plot(z,'b.')
end
I don't know if there is a neat way to force an array to be complex. To make z complex add this:
if isreal(z)
z = complex(z);
end
or this
z = complex(real(z),imag(z));
Giving: