Reputation: 17
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
Upvotes: 0
Views: 1484
Reputation: 112659
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);
Upvotes: 0
Reputation: 104474
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.
Upvotes: 3
Reputation: 91
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
Upvotes: 2