How do you format complex numbers for text output in matlab

前端 未结 3 1289
灰色年华
灰色年华 2021-01-12 05:39

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?

Usin

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 06:25

    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
    

提交回复
热议问题