Euclidean distance between the coordinates in the array - c#

I calculate euclidean distance in c#.
Point[] points = new Point[100];
I have the coordinates of the points I created in this array.I want to calculate the distance between all points.
for (int i = 1; i < k+1; i++)
{
X1 = points[i].X;
X2 = points[i + 1].X;
Y1 = points[i].Y;
Y2 = points[i + 1].Y;
result = Math.Sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
With this code I have calculated the distance between points (eg: distance between points a and b, distance between points c and d, etc.) but I couldn't calculate the distance between points a and c or the points b and b I want to calculate the distance between all points in this array. How do I do that?

You have to use 2 loops. The first loop assign values to X1 and the second loop assign values to X2.
This allows to calculate the Euclidean Distance between two points that aren't contiguous in the array.

You have to use 2 for loops to achieve that.
Also you would want to persist the euclidean distances between these points somewhere.

You probably want to go through the array twice.
Point[] points = new Point[100];
for(int i = 0; i < points.Length; i++)
for (int j = points.Length - 1; j >= i; j--)
{
float distance = 0;
if(i != j)
distance = CalculateDistance(points[i], points[j]);
// Do more stuff here
}
Obviously, you could simply run two for loops of equal lengths, but this will give you the same result twice. When i and j have the same value flipped (i = 10, j = 15 and later i = 15 and j = 10), you do the same calculation to get the same result. To prevent that I have my second loop only run about half the values to not redo calculations.
The CalculateDistance method does exactly the same as the code you have written before, in my case the following:
private static float CalculateDistance(Point point1, Point point2)
{
float X1 = point1.X;
float X2 = point1.Y;
float Y1 = point2.X;
float Y2 = point2.Y;
return (float)Math.Sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
This way I can reuse and reorder my calculations at any time, because I only have to move a single line. Note that you can always just use the floats as parameters instead of locals, but I felt like this way would make it more readable here in this example.
I also skipped the calculations when the distance was equal, because the same values were compared.

public void Euclidea()
{
double result;
int X1,X2,Y1,Y2;
for (int i = 1; i < k+1; i++)
{
X1 = points[i].X;
Y1 = points[i].Y;
for (int j = 0; j < k; j++)
{
X2 = points[j + 1].X;
Y2 = points[j + 1].Y;
result = Math.Sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
}
}
I solved the problem by typing this code
k=points.length()

Related

Using a weight function to procedurally generate terrain but its not giving me the expected result

I am trying to utilize a weight function from a paper titled "Dijkstra-based Terrain Generation Using Advanced Weight Functions". I have taken a weight function they provide and I have tried to implement it in C#. The output I am getting appears to be working but not completely. My knowledge of maths is not good enough for me to work out a solution.
Here is the weight function from the paper. The paper also defines a method for selecting nodes and calculating the weights but I don't believe this is required if I wish to just use this in isolation:
My current C# code. The data is being output into a Unity Terrain object.
for (int y = 0; y < Resolution; y++)
{
for (int x = 0; x < Resolution; x++)
{
//I tried to inteprite the expression here, this is probably not correct.
float dot = Vector3.Dot(WindDirection.normalized, new Vector3(x, y));
float ri = ReverseInterpolate(dot);
float inter = Interpolate(ri);
terrainheights[y, x] = Weight * inter;
}
}
My methods for Interpolation:
private float Interpolate(float value)
{
float x1 = 0;
float x2 = 1;
float y1 = 0;
float y2 = Weight;
float y = y1 + (value - x1) / (x2 - x1) * (y2 - y1);
return y;
}
private float ReverseInterpolate(float x)
{
float x1 = -1;
float x2 = 1;
float y1 = 0;
float y2 = 1;
float y = y1 + (x - x1)/ (x2 - x1) * (y2 - y1);
return y;
}
Finally is the result I get and the values for Weight and Wind Direction. as you can see, the effect is working slightly but not to the degree that I was hoping:
Any help would be very much appreciated!

Function that calculates diffrent positions from an array c#

I have a problem that I need help solving. Im supposed to create a function that calculates the distance between two positions. The positions are stored in two arrays, I can use as many parameters that I need to do this calculation
static double[] Latitudes = new double[] {
59.3261917, 57.7010496, 59.8939529, 65.5867395, 60.11021, 52.5069312, 48.859
};
static double[] Longitudes = new double[] {
17.7018773, 11.6136602, 10.6450348, 22.0422998, 24.7385057, 13.1445521, 2.2069765
};
I have been given an equation that will help me calculate the distance
distance = Math.sqrt( (x1 - x2)2 + (y1 - y2)2 )
My problem is that I can't get the elements from the arrays to the variables inside the function
Extract methods, split you problem into minor ones:
// Initial step:
// Distance between points
private static double Distance(double x1, double y1, double x2, double y2) {
return Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
// Next step:
// Distance between points given as arrays' items indexes
private static double Distance(double[] xs, double[] ys, int indexFrom, indexTo) {
return Distance(xs[indexFrom], ys[indexFrom], xs[indexTo], ys[indexTo]);
}
Then use
// What is the distance between 0-th and 2-nd point?
double result = Distance(Latitudes, Longitudes, 0, 2);
Console.WriteLine(result);
// What is the distance between all the points?
for (int from = 0; from < Math.Min(Latitudes.Length, Longitudes.Length); ++from)
for (int to = from + 1; to < Math.Min(Latitudes.Length, Longitudes.Length); ++to) {
Console.WriteLine($"Distance from item #{from} to item #{to} is {Distance(Latitudes, Longitudes, from, to)}");
}
Well first you need to decide which positions you want to compare. This would be done by index. Lets says you want to compare positions at index 0 with positions at index 2. Then the code to get the correct variables would be:
double x1 = Latitudes[0];
double y1 = Longitudes[0];
double x2 = Latitudes[2];
double y2 = Longitudes[2];
You can then feed those values into your function. Your function code is wrong and won't compile. The correct call for the function would be:
double distance = Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));
In the interest of providing a more complete function for your class, and keeping in mind that your arrays are static, this will allow you to get the distance from any two given points based on index. Also, I expect this is a homework assignment so I am leaning towards your requirement to be creating a function similar to this:
double CalculateDistance(int index1, int index2)
{
double x1 = Latitudes[index1];
double y1 = Longitudes[index1];
double x2 = Latitudes[index2];
double y2 = Longitudes[index2];
return Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));
}
You can then call this function as follows:
double distance = CalculateDistance(0, 2);
Show distance for all pairs
if (Latitudes.Length == Longitudes.Length)
{
for (int i = 0; i < Latitudes.Length - 1; i = i + 2)
{
double x1 = Longitudes[i];
double x2 = Longitudes[i + 1];
double y1 = Latitudes[i];
double y2 = Latitudes[i + 1];
double distance = Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));
Console.WriteLine($"x1 = {x1}; x2 = {x2}; y1 = {y1}; y2 = {y2}; distance {distance}");
}
}

EmguCV: Get coordinates of pixels in a line between two points

So here's my goal: I want to stop at each pixel on a line and do some processing on those pixels. Currently i'm using EmguCV for my image processing library. In openCV there is a method called LineIterator which you can use to iterate through the pixel in a line. However, I haven't found a method similar to this in EmguCV which is where I am getting stuck.
Currently, I can get the pixel values of all the pixels on a line between two predefined points using the Image.Sample method. For a grayscale image Image this returns a n-by-1 matrix with n being the number of pixels on that line. However, I am not able to get the coordinates of each pixel on that particular line corresponding to the pixel values in the n-by-1 matrix mentioned above. Hence, I am not able to do image processing on these pixels, even though I have their pixel values. Is there a way to do this on EmguCV?
Thank you.
I implemented the bresenham line algoritm for my own project
(converted to C# from the wikipedia article)
public static List<Point> GetBresenhamLine(Point p0, Point p1)
{
int x0 = p0.X;
int y0 = p0.Y;
int x1 = p1.X;
int y1 = p1.Y;
int dx = Math.Abs(x1 - x0);
int dy = Math.Abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
var points = new List<Point>();
while (true)
{
points.Add(new Point(x0, y0));
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 > -dy)
{
err = err - dy;
x0 = x0 + sx;
}
if (e2 < dx)
{
err = err + dx;
y0 = y0 + sy;
}
}
return points;
}
I implemented my own "Point" struct, but think it matches Emgu's.
I think this should take care of any special cases.
If (x1, y1) and (x2, y2) are two end points.
(x1, y1) ___________________ (x2, y2)
then you can get intermediate points by
for (int i = x1, i < x2; i++)
{
int x = i;
int y = (y1 + (y2-y1)/(x2-x1) * (x - x1)))
cout << "Points : " << x << " " << y << endl;
}

Iterate through N points that are perpendicular to another line

I have 1 line with 2 known points:
PointF p2_1 = new PointF();
p2_1.X = 100; // x1
p2_1.Y = 150; // y1
PointF p2_2 = new PointF();
p2_2.X = 800; // x2
p2_2.Y = 500; // y2
float dx = p2_2.X - p2_1.X;
float dy = p2_2.Y- p2_1.Y;
float slope = dy / dx; // slope m
float intercept = p2_1.Y - slope * p2_1.X; // intercept c
// y = mx + c
I'd like to iterate through 10 pixels to the left (or right) to 1 line (at x1, y1).
The red dots are the ones that I'd like process. Example:
for (int i = 10; i > 0; i--)
{
// start with distant coordinates
PointF new_point = new Point(); // (grab x,y, coords accordingly)
// repeat until I'm at (x1, y1)
}
How do I iterate through these coords?
A perpendicular vector will be of the form:
[-dy dx] where [dx dy] is your current vector. Once you have the perpendicular vector, you can normalize it (unit length), then iterate by a set amount:
float perp_dx = -dy / Math.sqrt(dy*dy+dx*dx); //normalized
float perp_dy = dx /Math.sqrt(dy*dy+dx*dx); //normalized
for(int i =0; /*logic here*/){
float new_x = perp_dx * i + start_x;
float new_y = perp_dy * i + start_y;
}
The line perpendicular to a given line has slope equal to the negative inverse of the slope of the given line.
The slope of the given line is (y2-y1) / (x2-x1)
So the red line has slope = - 1 / [(y2-y1) / (x2-x1)]
So each ith point on this line has coordinates (xi, yi) where
(yi - y1) / (xi - x1) = - 1 / (y2-y1) / x2-x1)
and is a multiple of one pixel fixed distance away from (x1, y1), i.e., where
(yi-y1) * (yi-y1) + (xi-x1) * (xi-x1) = i * i
what I would do is calculate what this increment vector (dx, dy) is for or between each point on the red line, and then just keep adding that increment in a loop that iterates 10 times.

Algorithm for finding a point in an irregular polygon

Imagagine I have a polygon like the following:
I am looking for a C# algorithm with whom I can find a point (could be the middlepoint or also a random point) inside any polygon.
For finding the center of mass I used the following algorithm:
private Point3d GetPolyLineCentroid(DBObject pObject, double pImageWidth, double pImageHeight)
{
Point2d[] pointArray = GetPointArrayOfRoomPolygon(pObject);
double centroidX = 0.0;
double centroidY = 0.0;
double signedArea = 0.0;
double x0 = 0.0; // Current vertex X
double y0 = 0.0; // Current vertex Y
double x1 = 0.0; // Next vertex X
double y1 = 0.0; // Next vertex Y
double a = 0.0; // Partial signed area
int i = 0;
for (i = 0; i < pointArray.Length - 1; ++i)
{
x0 = pointArray[i].X;
y0 = pointArray[i].Y;
x1 = pointArray[i + 1].X;
y1 = pointArray[i + 1].Y;
a = x0 * y1 - x1 * y0;
signedArea += a;
centroidX += (x0 + x1) * a;
centroidY += (y0 + y1) * a;
}
x0 = pointArray[i].X;
y0 = pointArray[i].Y;
x1 = pointArray[0].X;
y1 = pointArray[0].Y;
a = x0 * y1 - x1 * y0;
signedArea += a;
centroidX += (x0 + x1) * a;
centroidY += (y0 + y1) * a;
signedArea *= 0.5;
centroidX /= (6.0 * signedArea);
centroidY /= (6.0 * signedArea);
Point3d centroid = new Point3d(centroidX, centroidY, 0);
return centroid;
}
This works good with polygones like this:
But if my polygon has the form of a C or something like that this algorithmn does not work because the center off mass is outside the polygon.
Does anyone has an idea how to get always points inside any polygon?
You can use polygon triangulation to break your polygon apart into triangles.
One such algorithm is demonstrated using c# in this CodeProject article.
Once you have triangles, finding arbitrary points that lie within the triangle is easy. Any barycentric coordinate with a sum of 1.0 multiplied by the vertices of the triangle will give you a point inside the triangle.
The center can be derived using the barycentric coordinate [0.333333, 0.333333, 0.333333] :
float centerX = A.x * 0.333333 + B.x * 0.333333 + C.x * 0.3333333;
float centerY = A.y * 0.333333 + B.y * 0.333333 + C.y * 0.3333333;
or more simply:
float centerX = (A.x + B.x + C.x) / 3f;
float centerY = (A.y + B.y + C.y) / 3f;
Use This:
private Point getCentroid(pointArray)
{
double centroidX = 0.0;
double centroidY = 0.0;
for (int i = 0; i < pointArray.Length; i++)
{
centroidX += pointArray[i].X;
centroidY += pointArray[i].Y;`
}
centroidX /= pointArray.Length;
centroidY /= pointArray.Length;
return(new Point(centroidX ,centroidY));
}
this code is just to find Center of Mass of Polygon. To check whether a point is inside or outside polygon check this link http://bbs.dartmouth.edu/~fangq/MATH/download/source/Determining%20if%20a%20point%20lies%20on%20the%20interior%20of%20a%20polygon.htm

Categories

Resources