In: Advanced Math
In Matlab:
Any complex number z=a+bi can be given by its polar coordinates r and θ, where r=|z|=sqrt(a^2+b^2) is the magnitude and θ= arctan(ba) is the angle. Write a function that will return both the magnitude r and the angle θ of a given complex numberz=a+bi. You should not use the built-in functions abs and angle. You may use the built-in functions real and imag.
MATLAB Script (Run it as a script, not from command window):
close all
clear
clc
fprintf('Example
1\n-------------------------------------------\n')
c = 2+3i
[r,theta] = polar_coord(c)
fprintf('\nExample
2\n-------------------------------------------\n')
c = -2+3i
[r,theta] = polar_coord(c)
fprintf('\nExample
3\n-------------------------------------------\n')
c = -2-3i
[r,theta] = polar_coord(c)
fprintf('\nExample
4\n-------------------------------------------\n')
c = 2-3i
[r,theta] = polar_coord(c)
function [r,theta] = polar_coord(c)
% c - complex number, a + bi
a = real(c); b = imag(c);
r = sqrt(a^2 + b^2);
if a > 0 && b > 0
theta = atan(b/a);
else
if a < 0 && b > 0
theta = pi - atan(b/-a);
else
if a < 0 && b < 0
theta = atan(-b/-a) - pi;
else
theta = -atan(-b/a);
end
end
end
end
Output:
Example 1
-------------------------------------------
c =
2.0000 + 3.0000i
r =
3.6056
theta =
0.9828
Example 2
-------------------------------------------
c =
-2.0000 + 3.0000i
r =
3.6056
theta =
2.1588
Example 3
-------------------------------------------
c =
-2.0000 - 3.0000i
r =
3.6056
theta =
-2.1588
Example 4
-------------------------------------------
c =
2.0000 - 3.0000i
r =
3.6056
theta =
-0.9828