How do you format complex numbers for text output in matlab

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

提交回复
热议问题