How to use fprintf with complex values

Viewed 1118

My code computes the real and imaginary parts of V1 as follows:

V1=term1/term3 + term2/term3 * i
fprintf( 'Slope V1 = %.4f\n', real(V1), imag(V1) )

I want to output the complex number V1 as follows:

Slope of V1 = real(V1) + imag(V1) * i

I never seem to get the %4.f notation correct. Can someone give me a start with this, please? I am not sure how to handle the + sign.

V1=term1/term3 + term2/term3 *i
fprintf( 'Slope V1 = %.4f\n', real(V1), imag(V1) )

Outputs

Slope V1 = 0.0000
Slope V1 = 1.4142

I want to have output

Slope V1 = 0.0000+1.4142i

Sincerely, MM

3 Answers

Did you try using two format specifiers for the two values you want to print?

fprintf( 'Slope V1 = %.4f + %.4f i\n', real(V1), imag(V1) )

Or, even better (as Hunter Jiang suggested):

fprintf( 'Slope V1 = %.4f%+.4fi\n', real(V1), imag(V1) )

...by including the + in the format specifier, the second number will always be preceded by either a "-" or a "+" depending on the sign of the value. For negative imaginary numbers this prevents printing "+ -".

If you want to display a value you have two options:

1. disp(z);

2. fprintf("Slope V1 = %.4f %+.fi\n', real(V1), imag(V1)")

note that disp ends with a new line while fprintf doesn't that's why we use ' \n '

As for the %4.f you use it if you want the number to be indented by 4 whitespaces and take just the integer part. if you want to set the precision to 4 digits after the decimal point you would use %.4f

Let's say we want to display 12.1234

%4.f:   12
%.4f:12.1234
%.2f:12.12
%10.2f:        12.12

You can use num2str, which automatically handles complex numbers:

fprintf(['Slope V1 = ' num2str(1+1j, '%.4f')])

or

fprintf('Slope V1 = %s', num2str(1+1j, '%.4f'))
Related