How do you format complex numbers for text output in matlab

前端 未结 3 1290
灰色年华
灰色年华 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:22

    I don't know if there is an easy way, but you can write your own format function (the hard way):

    function mainFunction()
        st = sprintfe('%d is imaginary, but %d is real!',1+3i,5);
        disp(st);
    
        st = sprintfe('%f + %f = %f',i,3,3+i);
        disp(st);
    end
    
    function stOut = sprintfe(st,varargin) %Converts complex numbers.
        for i=1:numel(varargin)
            places = strfind(st,'%');
            currentVar = varargin{i};
            if isnumeric(currentVar) && abs(imag(currentVar))> eps
                index = places(i);
                formatSpecifier = st(index:index+1);
                varargin{i} = fc(currentVar,formatSpecifier);
                st(index+1) = 's';
            end
        end
        stOut = sprintf(st,varargin{:});
    end
    
    function st = fc(x,formatSpecifier)
        st = sprintf([formatSpecifier '+' formatSpecifier 'i'],real(x),imag(x));
    end
    

    This solution suffers from some bugs, (does not handle %2d,%3f) but you get the general idea.

    Here are the results:

    >> mainFuncio
    1+3i is imaginary, but 5 is real!
    0.000000+1.000000i + 3.000000 = 3.000000+1.000000i
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-12 06:27

    Address the real and imaginary parts separately:

    x = -sqrt(-2)+2;
    fprintf('%7.4f%+7.4fi\n',real(x),imag(x))
    

    or convert to string first with num2str()

    num2str(x,'%7.4f')
    
    0 讨论(0)
提交回复
热议问题