Calculate area of polygon recursively - matlab

I had to calculate any polygon given cordinates of point in 'x-vector','y-vector' (only thing I know is the cordinates are ordered clockwise and polygons like hourglass are not included).
I tried writing this code:
function [areaofit] = Polygarea(xs,ys,cor,prevsum)
if(length(xs)~=length(ys))
disp('dimentions error!please try again');
end
if(nargin==2)
cor=1;
prevsum=0;
end
if(cor==length(xs)-1)
areaofit=prevsum;
figure(1);
fill(xs,ys,'r');
title(['Area = ' num2str(areaofit)]);
end
if(cor~=length(xs)-1)
mat=[xs(1) ys(1) 1;zeros(2,3)];
for k=2:3
mat(k,1)=xs(cor+k-1);
mat(k,2)=ys(cor+k-1);
mat(k,3)=1;
end
farea=prevsum+abs(det(mat))/2;
Polygarea(xs,ys,cor+1,farea);
end
The function does work with any convex polygon but there are concave polygons it does work with (like 'stars' e.g ). What can be improved in my solution? thanks

I think you need to modify this line:
farea=prevsum+abs(det(mat))/2;
to
farea=prevsum+det(mat)/2;
Like this, the concavities in your polygon will add or subtract areas according to what direction they sweep the 0..2π range. To ensure final positive values for your area, there should be something like areaofit=abs(prevsum);

Related

How to attribute intersection points between poly and lineseg to poly

I'm trying to plot an animal's trajectory from a set of coordinates as a line segment. I want to see how many coordinates are plotted inside a circular zone vs outside. I think that coordinates which intersect with the circle are being counted as both inside and outside, but I would like them to be strictly counted as inside. This is what I have so far:
[in,out] = intersect(circle_poly,trajectory);
plot(circle_poly)
hold on
plot(in(:,1),in(:,2),'b',out(:,1),out(:,2),'r')
legend('Polygon','Inside','Outside','Location','NorthWest')
num_frames_in = numel([in]) %count num elements/frames in polygon
num_frames_out = numel([out]) %count num element/frames outside polygon
total_frames = num_frames_in + num_frames_out
Any help would be really appreciated since I'm new to Matlab!

How to get coords between 2 points

I cannot find exactly what I'm looking for or reading google documentation I missed it, I just need a function or whatever to submit 2 point, start and end, and get X waypoint in between.
Is there some api like "www.somesite.com/api.php?start=43.12,12.23&end=44.12,12.23&number_of_waypoints=5" that return some json?
thank you!
First of all, this will require working with geodesics, which are the shortest lines passing through two points around the Earth, assuming the Earth is an ellipsoid. WGS84 is the standard coordinate system you will see most widely used for "latitude + longitude" coordinates, and this assumes the Earth is an ellipsoid.
To solve this problem, you first need to find the azimuth (bearing angle from north) and distance between two coordinates. The way to calculate this is by solving the inverse geodesic problem.
Once we have this distance (let's say in metres), we can divide it by n, where n - 1 is the number of waypoints we want in between the line. This gives us the distance d metres between each waypoint.
Now, we need to plot points at intervals of d metres along this line. To do this, we can solve the direct geodesic problem. This gives us a new set of coordinates after moving a given distance from a given point with a given azimuth. We can do this repeatedly to get new points moving d metres from the previous point each time. One thing to note with this is that the resultant azimuth to the end of the line from different points within the line will vary, so the destination azimuth must be obtained after each stage and used for calculating the next point.
Solving the direct and inverse geodesic problems requires mathematical formulas, of which multiple are available. However, for your PHP application, you are probably best not trying to implement these yourself, but instead use a library which can do this for you. One popular library for PHP which does this is called phpgeo.
Here's an example of how this might be implemented with phpgeo:
<?php
use Location\Coordinate;
use Location\Distance\Vincenty;
use Location\Bearing\BearingEllipsoidal;
$numPoints = 5;
$coordsA = new Coordinate(50.0, 0.0);
$coordsB = new Coordinate(51.0, 1.0);
$bearingCalculator = new BearingEllipsoidal();
$distanceCalculator = new Vincenty();
// Inverse geodesic problem
// Calculate total length of line between coords
$totalDistance = $distanceCalculator->getDistance($coordsA, $coordsB);
$intervalDistance = $totalDistance / ($numPoints + 1);
// Inverse geodesic problem
// Calculate angle to destination
$currentBearing = $bearingCalculator->calculateBearing($coordsA, $coordsB);
$currentCoords = $coordsA;
$points = [];
for ($i = 0; $i < $numPoints; $i++) {
// Direct geodesic problem
// Calculate new point along line
$currentCoords =
$bearingCalculator->calculateDestination($currentCoords,
$currentBearing,
$intervalDistance);
// Add these new coordinates to the list
array_push($points, $currentCoords);
// Inverse geodesic problem
// Recalculate angle to destination
$currentBearing =
$bearingCalculator->calculateBearing($currentCoords,
$coordsB);
}
// Print out the list of points
foreach ($points as $point) {
echo "{$point->getLat()}, {$point->getLng()}\n";
}

How to draw the lines or edges of a cone in matlab

I am trying to draw the lines or the edges of a cone using plot3 in matlab. Any help please? I do not need the surface. I need the edges only. SO that I can patch something on it. A useful link. But i need the circle at the bottom:
https://patentimages.storage.googleapis.com/US8514658B2/US08514658-20130820-D00021.png
Few horizontal lines are fine. But no tilted line as i need to patch something inside.
cylinder is your friend here...
You just need to pass it a vector of radii* and transpose the output*...
* negative radii tending to zero will flip the order so the apex is on top...
* so it draws rings not lines from the base to the apex
numRings = 10;
numPointsAround = 100;
[x,y,z] = cylinder(linspace(-1,0,nlines),numPointsAround);
plot3(y.',x.',z.','-k')
I think this is what you want. Most of the answer is directly taken from the above answer by #RTL.
numRings = 2;
numPointsAround = 100;
[x,y,z] = cylinder(linspace(-1,0,numRings),numPointsAround);
plot3(y.',x.',z.','-k')
hold on;line([-0.5878;0], [0.809;0],[0;1]);
hold on;line([0.9511;0], [-0.309;0],[0;1]);
axis square

MATLAB how to Draw a circle around a chosen node in a graph?

l have generated a topology of a network with 200 nodes.than l want to draw a circle with black color around a choosen node(satisfying a certain condition IF (condition) ).
to simplify let the user introduce the the index of the node to circle with the black color.
here is my code of the generated topology.l need to add wich instructions to draw the circle around the choosen node ?
X=100;
Y=100;
N=200; %number of nodes
nodesX(1)=rand*X;
nodesY(1)=rand*Y;
for i=2:N
nodesX(i)=rand*X;
nodesY(i)=rand*Y;
d(i-1) =((nodesX(i)-nodesX(i-1)).^2+(nodesY(i)-nodesY(i-1)).^2).^0.5;
while (d(i-1)>200)
nodesX(i)=rand*X;
nodesY(i)=rand*Y;
d(i-1) =((nodesX(i)-nodesX(i-1)).^2+(nodesY(i)-nodesY(i-1)).^2).^0.5;
end
end
h_old=plot(nodesX,nodesY,'m*');
labels=[1:N]';
labels=num2str(labels);
text(nodesX,nodesY,labels);
xlabel('X (Meters)');
ylabel('Y (Meters)');
title(['Network Topology with',num2str(N),'nodes']);
hold on
for k=1:N;
for j=1:N;
if (k~=j)
d=((nodesX(k)-nodesX(j))^2+(nodesY(k)-nodesY(j))^2)^0.5;
end
if (k~=j);
if(d < 50);
line([nodesX(k),nodesX(j)],[nodesY(k),nodesY(j)]);
end
end
end;
end;
Split it into two tasks:
Task 1:
Define a simple function to draw a circle. A cheap and dirty way is to use polar expressions.
function [] = circle(center_x,center_y,r)
theta = 0:0.01:2*pi;
x = center_x + r*cos(theta);
y = center_y + r*sin(theta);
plot(x,y,'k','LineWidth',2)
Task 2:
Pass this function the NodeX and NodeY values of the indexed node as the point at which the circle is centered. You can set the radius of the circle as per your choice. Using r=1 and picking an arbitrary index, I got:
Just one caveat: Make sure your axis are square. Otherwise, a circle might look like an ellipse. If you want to draw a circle around non-square axis, then you can modify the code to generate an ellipse instead.

Plotting intersection of planar surfaces in matlab

I am looking to plot the intersection of two surfaces(patches) lying the same plane in MATLAB.
As you can see in the above picture the green circle intersects four red rectangles.I want to plot out(or patch) only the four intersections.How do I proceed?
I tried to plot points on the circular patch which lies outside the intersection of one rectangle and circle using conditional statements.But MATLAB throws an error.Here is the code snippet.
[p,q] = size(points);
for s=1:1:q;
t = points(1,s);
if (points(1,s) >= Pa3(1,1)) && (points(1,s) <= Pa2(1,1)) && (points(2,s) >= Pa3(1,2)) && (points(2,s) <= Pa4(1,2))
points(1,s) = 0;points(2,s) = 0;
end
end
fill3(points(1,:), points(2,:), points(3,:), 'g');
The above code throws an error at if statement.Basically in the code "points" represent all the points in the green circle.Pa1,Pa2,Pa3,Pa4 represent the vertices of the left top corner rectangle with Pa1 being the left corner top vertex and Pa2,Pa3,Pa4 following in clockwise manner.
Thanks
Patches are defined by polygons, and what you are looking for is the intersection of two polygons which itself is a polygon.
If you have the Mapping Toolbox, you can use polybool to compute the intersection and other logical operations on polygons.
If not, have a look at the submission Polygon_Intersection on the Matlab File Exchange.
See also intersection and union of polygons.