Using fprintf for complex numbers
177 views (last 30 days)
Show older comments
Savannah Roemer
on 27 Aug 2019
Hi, I have
Z1= sqrt(3) * exp((pi*i)/4)
Z2= 2 * exp((pi*i)/6)
Z3= sqrt(3) * exp((3*pi*i)/4)
Z4= 2 * exp(pi*i)
Z5= 2 * exp(-pi*i)
And I would like something like
Real Complex
Z1 1.2247 + 1.2247i
Z2 1.7321 + 1.0000i
Z3 -1.2247 + 1.2247i
Z4 -2.0000 + 0.0000i
Z5 -2.0000 - 0.0000i
Using fprintf, I would think...
Thanks for your help!
0 Comments
Accepted Answer
KALYAN ACHARJYA
on 27 Aug 2019
Edited: KALYAN ACHARJYA
on 27 Aug 2019
One Way:
Z1= sqrt(3) * exp((pi*i)/4)
fprintf('%f + %fi',real(Z1),imag(Z1))
More:
Z1= sqrt(3) * exp((pi*i)/4);
Z2= 2 * exp((pi*i)/6);
Z3= sqrt(3) * exp((3*pi*i)/4);
Z4= 2 * exp(pi*i);
Z5= 2 * exp(-pi*i);
disp(' Real Complex')
fprintf('\nZ1 %.4f + %.4fi',real(Z1),imag(Z1));
fprintf('\nZ2 %.4f + %.4fi',real(Z2),imag(Z2));
fprintf('\nZ3 %.4f + %.4fi',real(Z3),imag(Z3));
fprintf('\nZ4 %.4f + %.4fi',real(Z4),imag(Z4));
fprintf('\nZ5 %.4f + %.4fi',real(Z5),imag(Z5));
Result:
2 Comments
KALYAN ACHARJYA
on 27 Aug 2019
No Savannah, those MPVs are my Guru here.. continually they are teaching me .
Specially @Walter Roberson, @Image Analyst @Madhan @Jan .and...many more....
Anyway thanks for your kind words!
More Answers (2)
Adam Danz
on 24 Nov 2023
Edited: Adam Danz
on 24 Nov 2023
a = -2*sqrt(-3)+5/3
num2str(a)
num2str(a, 2) % specify precision
You would enter this as a string in fprintf
ijstr = num2str(a,3);
fprintf('%s %s', 'Z1', ijstr)
Note that this method may return strings in undesired formats such as,
num2str(160, 2)
0 Comments
Walter Roberson
on 27 Aug 2019
Edited: Walter Roberson
on 27 Aug 2019
fprintf() always ignores imaginary components of numbers. You need to ask to output the real() and imaginary() components separately,
fprintf('%2s %7.4f %+7.4fi\n', 'Z1', real(Z1), imag(Z1))
0 Comments
See Also
Categories
Find more on Contour Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!