I have a complex number that I want to output as text using the fprintf command. I don't see a formatspec for complex numbers. Is there an easy way to do this?
Using the format spec for fixed-point is only outputting the real part.
In MATLAB®, i and j represent the basic imaginary unit. You can use them to create complex numbers such as 2i+5 . You can also determine the real and imaginary parts of complex numbers and compute other common values such as phase and angle.
Y = imag( Z ) returns the imaginary part of each element in array Z .
Description. X = real( Z ) returns the real part of each element in array Z .
According to the documentation of fprintf and sprintf
Numeric conversions print only the real component of complex numbers.
So for a complex value z
you can use this
sprintf('%f + %fi\n', z, z/1i)
for example
>> z=2+3i;
>> sprintf('%f + %fi\n', z, z/1i)
2.000000 + 3.000000i
You can wrap it in an anonymous function to get it easily as a string
zprintf = @(z) sprintf('%f + %fi', z, z/1i)
then
>> zprintf(2+3i)
ans =
2.000000 + 3.000000i
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