How do you format complex numbers for text output in matlab

I have a complex number that I want to print as text using the fprintf command. I do not see specpec for complex numbers. Is there an easy way to do this?

Using the format specification for a fixed point only outputs the real part.

+7
source share
3 answers

According to fprintf and sprintf documentation

Numeric conversions print only the real component of complex numbers.

So, for the complex value of z you can use this

 sprintf('%f + %fi\n', z, z/1i) 

eg

 >> z=2+3i; >> sprintf('%f + %fi\n', z, z/1i) 2.000000 + 3.000000i 

You can wrap it in an anonymous function to easily get it as a string

 zprintf = @(z) sprintf('%f + %fi', z, z/1i) 

then

 >> zprintf(2+3i) ans = 2.000000 + 3.000000i 
+5
source

Refer to the real and imaginary parts separately:

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

or first convert to string using num2str()

 num2str(x,'%7.4f') 
+3
source

I don't know if there is an easy way, but you can write your own format function (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 errors (does not handle% 2d,% 3f), but you get a 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 
+1
source

All Articles