Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format complex numbers for text output in matlab

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.

like image 214
Jim Avatar asked Jun 30 '13 22:06

Jim


People also ask

How do you specify complex numbers in MATLAB?

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.

How do i print imaginary parts in MATLAB?

Y = imag( Z ) returns the imaginary part of each element in array Z .

How do you display real part of complex numbers in MATLAB?

Description. X = real( Z ) returns the real part of each element in array Z .


1 Answers

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
like image 103
Mohsen Nosratinia Avatar answered Oct 20 '22 10:10

Mohsen Nosratinia