Printing polar and trigonometric coordinates in Matlab

Viewed 45

I am trying to write a function which takes the value x and y in cartesian coordinates as the input and outputs the polar and trigonometric forms. I would like the output to contain the exponential and sin/cos rather than the actual value. For example, if the cartesian is z=1i, I would like the function to output z=sqrt(2)e^(ipi/4) and z=sqrt(2)(cos(pi/4)+Isin(pi/4). How can I do this?

function coordinates(x,y)

r=sqrt(x.^2+y.^2);

theta=atan(y./x);

polarcoord=rexp(itheta)

trigcoord=r*(cos(theta)+i*sin(theta))

end

This gives me the following output :

polarcoord =

1.0000 + 1.0000i

trigcoord =

1.0000 + 1.0000i

thanks

1 Answers

Welcome to SO! You are using functions (sqrt(x) calculates the actual square root of x, exp(x) the exponential, ... So that is why you get the actual value, not the formula expression.

So, a possible way to output the formula is using strings to print the functions without calling them. Then, what you need to do is calculate the values you want inside the sqrt() and the fraction which * pi and add them to a string array. We can do that using square brackets [ ], the function num2string() and the operator + to add strings in the same string array:

function coordinates(x,y)

[num,dem] = rat(atan(y./x)/pi);  
    % rat converts theta to fraction
    % divide by pi to extract pi from theta    

root = ["sqrt(" + num2str(x^2+y^2) + ")"]; % i.e "sqrt(2)"
pi_value = ["(" + num2str(num) + "*pi/" + num2str(dem) + ")"]; 
    % i.e "(1*pi/4)" o "(2*pi/5)"...

polarcoord = ["z = " + root + "e^(i" + pi_value]

trigcoord = ["z = " + root + "(cos" + pi_value + ")+i*sin" + pi_value]
   
end

Example:

coordinates(1,1)

Outputs:

polarcoord = "z = sqrt(2)e^(i(1*pi/4)"

trigcoord = "z = sqrt(2)(cos(1pi/4))+isin(1*pi/4)"

To calculate the fraction we use rat() function to obtain numerator and denominator from the double output of atan(y./x) and we divide by pi to extract its value from the theta value (we are representing pi already in the string).

Related