Matlab: finding polar coordinates from cartesian coordinates

1.4k Views Asked by At

I am a newcomer to Matlab and programming in general. My Cartesian to polar conversion function that I wrote doesn't work.

syms x y
function [r,theta]=something[x,y] 
  r=(x^2+y^2)^.5
  theta=atan(x/y)
end
3

There are 3 best solutions below

0
On

You can use the cart2pol function:

[theta, rho] = cart2pol(x, y)

Or do this:

  theta = atan2(y, x)     % use atan2() instead of atan()
  rho = sqrt(x.^2 + y.^2) % use sqrt() instead of .^5
0
On

What you are trying to do is create a function script file, but you have a non-function declaration statement at the beginning of your file. You can't do this. As such, you need to remove the syms x y statement at the beginning of your code. Also, you aren't declaring your function properly. You need to use round braces, not square braces to define your input parameters.

I would also use atan2 instead of atan because it finds the proper four-quadrant arc-tangent of the Cartesian coordinates. Also, use sqrt not ^.5 to take the square root. It's more stable. Also, to properly handle vector inputs, you need to make sure that x and y use .^2 in the r calculation and not ^2. Therefore, do this instead:

function [r,theta]=something(x,y) %// Change
r=sqrt(x.^2 + y.^2); %// Change
theta=atan2(y, x); %// Change
end

Place that into a file called something.m, then you can go into the command prompt and do this:

[r,theta] = something(x,y);

x and y are the x and y values of your Cartesian coordinates. What's great is that x and y can be a single value, a vector or a matrix of any size.

0
On

This is very easy with complex numbers. Specifically, if the given Cartesian coordinates are interpreted as the real and imaginary parts of a complex number, then the polar coordinates are the magnitude (abs) and argument (angle) of that complex number:

>> z = x+1j*y;
>> r = abs(z);
>> theta = angle(z);