Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute distance in Cartesian Coordinate System in Mathematica

Analyzing Eye-movements on a screen, I set my origin to the bottom left corner of it (Hard to modify at that point).

Trying to compute distance between some points and the center of the screen I use the simple formula displayed below. Problem is that using this in conditional statement, it gets ugly.

Sqrt[
(
(fixationX - centerX)^2 + (fixationY - centerY)^2
)
]

Is there a way to customize Norm to compute distance between points and not between a point and the origin ?

Or in my case, set the origin to be at the "center" of the current coordinate system ?

like image 245
500 Avatar asked Jun 12 '11 14:06

500


2 Answers

A slight variation of Simon's method is to use a default value in the function, rather than a global variable ($Center).

Suppose your default origin is (5, 5), then:

myNorm[pos:{_, _}, center_:{5, 5}] := EuclideanDistance[pos, center]

Notice the use of _:{5, 5} to define the default value.

Now you can do:

myNorm[{5, 7}]

(* Out[]= 2 *)

Or temporarily use a different the center with:

myNorm[{5, 7}, {8, 8}]

(* Out[]= Sqrt[10] *)

For this simple function, you could use EuclideanDistance in the second case instead, but I hope you can see the utility of this method were the definition of myNorm more complex.

The downside to this method is that you cannot easily change the default center.


Another variation that does allow one to easily change the default center, but is more verbose, is to use Options:

Options[myNorm2] = {Center -> {5, 5}};

myNorm2[pos : {_, _}, OptionsPattern[]] := 
 EuclideanDistance[pos, OptionValue[Center]]

Syntax is:

myNorm2[{5, 7}]

myNorm2[{5, 7}, Center -> {8, 8}]
   2
   Sqrt[10]

Changing the default center:

SetOptions[myNorm2, Center -> {8, 8}];

myNorm2[{5, 7}]
   Sqrt[10]
like image 90
Mr.Wizard Avatar answered Nov 18 '22 02:11

Mr.Wizard


Can you just use EuclideanDistance

In[1]:= EuclideanDistance[{x,y}, {cx,cy}]
Out[1]= Sqrt[Abs[-cx +x ]^2 + Abs[-cy + y]^2]

Or define a $Center and a new CNorm, e.g.

$Center = {cx, cy};
CNorm[pos:{x_, y_}] := EuclideanDistance[pos, $Center]
like image 26
Simon Avatar answered Nov 18 '22 02:11

Simon