Group Abstract Group Abstract

Message Boards Message Boards

0
|
4.4K Views
|
5 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Convert polar to cartesian coordinates without built in commands?

Posted 9 years ago

First I just want to say I am NOT going to use the built in command FromPolarCoordinates, I am attempting to write my own function that will do the same thing..

I currently am able to convert between one pair of polar coordinates and Cartesian with the following code and usage of replacement rules:

Clear[blah],
blah[r_,theta_]:= {r,theta}/. {r -> r*Cos[theta], theta -> r*Sin[theta]};
blah[1,pi/4]

which produces

{1/Sqrt[2], 1/Sqrt[2]}

But what if I wanted to enter a list into my blah function, such as blah[{1,pi/4},{pi/4,pi/4}] and so on...? I was thinking the "Switch" command might come in handy

Thanks,

B

POSTED BY: Brandon Davis
5 Replies
Posted 9 years ago

Hey Brandon,

the code I supplied works perfectly for me. I have defined blah[..] twice, but one definition is conditional (/; MatrixQ[ .. ]). This is similiar to functional overloading in C++. I am running M11.0.1 on Windows10.

Regards,

Michael

POSTED BY: Michael Helmle

One way would be this:

Clear[blah];
blah[r_ /; Not[Head[r] === List], 
   theta_] := {r, theta} /. {r -> r*Cos[theta], theta -> r*Sin[theta]};
blah[pts___List] := blah @@@ {pts}

so that blah[{r1, theta1}, {r2, theta2}] gives the list you want.

POSTED BY: Gianluca Gorni
Posted 9 years ago

Hey Gianluca,

This code works great but the second output doesn't evaluate correctly.

Thanks for your input!!

B

POSTED BY: Brandon Davis
Posted 9 years ago

Hello Brandon,

you could do it this way:

In[1]:= blah[polar_] := polar[[1]] {Cos[polar[[2]]], Sin[polar[[2]]]}
blah[polar_] := Map[blah[#] &, polar] /; MatrixQ[polar]

In[3]:= lst = RandomReal[5, {10, 2}];

In[4]:= blah[lst]

Out[4]= {{-1.33346, -1.73984}, {-4.74456, -1.01628}, {1.07804, 
  0.471759}, {2.08963, 3.48567}, {2.89406, 2.14102}, {3.02783, 
  0.775746}, {0.019113, 0.0156172}, {0.0448616, -0.754736}, {2.85285, 
  1.6724}, {1.62422, 1.72386}}

In[5]:= blah[{1., 0.5}]

Out[5]= {0.877583, 0.479426}

Regards,

Michael

POSTED BY: Michael Helmle
Posted 9 years ago

Hey Michael,

This is a cool way to go about it. I was trying something along the lines of:

Clear[blah,bleh],
blah[r_,theta_]:= {r,theta}/. {r -> r*Cos[theta], theta -> r*Sin[theta]};
bleh[list_]:=list /. List -> blah[r,Theta];
bleh[{1,pi/4},{pi/4,pi/4}]

Obviously this is wrong because all I get as an output is just bleh[{1,pi/4},{pi/4,pi/4}] but I feel like I am somewhat in the right direction. I tried to run your code but you have "polar" defined twice so there was an error.

But anyways, I appreciate your help!

B

POSTED BY: Brandon Davis
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard