Math - Generating Point in Rotated 2D Disc in 3D Space - matlab

I've been trying to generate points along the ring of a 2D disc (both translated and rotated) in 3D space using only the disc's position and normal.
I've been using the following code to generate points and have been testing it in Matlab (but will be utilising this in c#) to check that the points are generated correctly, however it doesn't seem to be generating points correctly.
numPoints = 25;
radius = 1;
pos = [1; 2; 3];
dir = normc([3; 4; 6]); % normalised
function [pointsT, points] = GenerateDiscPoints(numPoints, radius, pos, dir)
points = zeros(numPoints, 3);
pointsT = zeros(numPoints, 3);
% Angle between points
angle = 2 * pi / numPoints;
for i = 1:numPoints+1
% Current point angle
theta = angle * i;
% Generate point in flat disc (y is vertical axis in Unity)
x = radius * cos(theta) + pos(1);
y = 0 + pos(2);
z = radius * sin(theta) + pos(3);
% Save points
points(i, 1) = x;
points(i, 2) = y;
points(i, 3) = z;
% Calculate t value to translate points
t = (dir(1) * pos(1) - dir(1) * x + dir(2) * pos(2) - dir(2) * y + dir(3) * pos(3) - dir(3) * z) / (dir(1)*dir(1) + dir(2)*dir(2) + dir(3)*dir(3));
% Translate points to correct location
xT = x + t*dir(1);
yT = y + t*dir(2);
zT = z + t*dir(3);
% Save translated points
pointsT(i, 1) = xT;
pointsT(i, 2) = yT;
pointsT(i, 3) = zT;
end
% Plot
figure;
hold all;
grid on;
scatter3(points(:,1), points(:,2), points(:,3), 25, 'r');
scatter3(pointsT(:,1), pointsT(:,2), pointsT(:,3), 25, 'g');
p3 = line([pos(1) pos(1)+dir(1)], [pos(2) pos(2)+dir(2)], [pos(3) pos(3)+dir(3)]);
set(p3, 'Color', 'blue');
end
The blue line is the normal of the disc, the red points are the points before being translated, and the green points are the points after being translated. To my eye it appears that the translated points don't seem to be generating in a disc that has the normal specified.
What's wrong with my current algorithm? What would a better way to do this be?

A simple linear translation along the direction of dir is insufficient - you'll end up with the projection of the circle on the plane at pos with normal dir, i.e. an ellipse.
You could either:
Use quaternions to construct a rotation matrix to re-orientate your generated circle to dir.
Creating this quaternion: https://stackoverflow.com/a/1171995/8204776
Converting it to a matrix: https://stackoverflow.com/a/1556470/8204776
or
Construct an orthogonal basis at pos where one axis is dir.
Easy way to do this:
Check if the X-axis is parallel to dir - ideally do abs(dot(dir, X)) < 0.8 (assuming both are normalized), so they are not too close to each other
If (1) is true then take dir2 = Y, else dir2 = X.
To create the first basis vector, A = normalize(cross(dir, dir2)).
To create the second, B = cross(dir, A).
Now you can generate points at each value of theta by pos + radius * (A * cos(theta) + B * sin(theta)) (in vector notation).

Related

Coloring sections of sphere, some regions end up with unassigned colors

I am trying to create a spherical histogram and I have found an addon that creates a spherical histogram, however it uses equal area quadrilaterals and for my purposes I would like to preserve the lines found on the traditional sphere created with MATLAB so they can match latitude and longitude lines.
I found a way to color a given subset of the sphere by setting the min/max Azimuth and Elevation values of the region I want to shade, and to try and test out coloring each cell of the sphere I have tried dividing the azimuth and elevation total angles by a given n value and looping through to assign a random color to each cell. This works for about 2/3s of the cells, however there are random azimuth/elevation sections where there is no color assigned, indicating some type of problem with the surf() function presumably. I thought the count n for the sphere being only 20 might cause rounding errors that would be the main contributing factor for this, but there are proportionally similar sized gaps found for a 50x50 cell sphere as well. My best guess is some kind of rounding precision error that causes the given cell region to skip assigning a color due to the given bounds being too far from matching an actual cell, essentially having the given bounds being in between two lines. How can I iterate through every cell based on its azimuth and elevation range for a given sphere of size n?
n = 20;
%// Change your ranges here
minAzimuth = -180;
maxAzimuth = 180;
minElevation = 0;
maxElevation = 180;
%// Compute angles - assuming that you have already run the code for sphere
[x,y,z] = sphere(n);
theta = acosd(z);
phi = atan2d(y, x);
%%%%%// Begin highlighting logic
ind = (phi >= minAzimuth & phi <= maxAzimuth) & ...
(theta >= minElevation & theta <= maxElevation); % // Find those indices
x2 = x; y2 = y; z2 = z; %// Make a copy of the sphere co-ordinates
x2(~ind) = NaN; y2(~ind) = NaN; z2(~ind) = NaN; %// Set those out of bounds to NaN
%%%%%// Draw our original sphere and then the region we want on top
r = 1;
surf(r.*x,r.*y,r.*z,'FaceColor', 'white', 'FaceAlpha',0); %// Base sphere
hold on;
%surf(r.*x2,r.*y2,r.*z2,'FaceColor','red', 'FaceAlpha',0.5); %// Highlighted portion
%// Adjust viewing angle for better view
for countAz = 1:1:n
current_minAzimuth = -180 + (countAz-1) * (360/n);
current_maxAzimuth = -180 + (countAz) * (360/n);
for countE = 1:1:n
current_minElevation = 0 + (countE-1) * (180/n);
current_maxElevation = 0 + (countE) * (180/n);
theta = acosd(z);
phi = atan2d(y, x);
%%%%%// Begin highlighting logic
ind = (phi >= current_minAzimuth & phi <= current_maxAzimuth) & ...
(theta >= current_minElevation & theta <= current_maxElevation); % // Find those indices
x2 = x; y2 = y; z2 = z; %// Make a copy of the sphere co-ordinates
x2(~ind) = NaN; y2(~ind) = NaN; z2(~ind) = NaN;
random_color = rand(1,3);
surf(r.*x2,r.*y2,r.*z2,'FaceColor',random_color, 'FaceAlpha',1);
end
end
axis equal;
view(40,40);
Here is an n=50 sphere:
And here is an n=20 sphere
You're doing more conversions to and from spherical/Cartesian coordinates than you need to, and subsequently doing more floating point comparisons than required.
You are essentially just looping through all of the 2x2 index blocks in the x, y and z arrays.
It's simpler to just directly create the index arrays you're trying to use and then pull out those values of the existing surface coordinates.
for countAz = 1:1:n
for countE = 1:1:n
% Linear index for a 2x2 patch of the matrices
idx = countAz + [0,1,n+(1:2)] + (countE-1)*(n+1);
% Pull out the coordinates, reshape for surf
x2 = x(idx); x2 = reshape(x2,2,2);
y2 = y(idx); y2 = reshape(y2,2,2);
z2 = z(idx); z2 = reshape(z2,2,2);
random_color = rand(1,3);
surf(r*x2,r*y2,r*z2,'FaceColor',random_color, 'FaceAlpha',1);
end
end

How do I visualize the intersection of spheres in MATLAB?

It seems this question has been asked in a few places (including on SO). I recently came across the need for this when visualizing results of a trilateration problem.
In almost every case, the answer directs the inquiry to look at Wolfram for the math but excludes any code. The math really is a great reference, but if I'm asking a question on programming, some code might help as well. (It certainly is also appreciated when answers to a code question avoid pithy comments like "writing the code is trivial").
So how can one visualize the intersection of spheres in MATLAB? I have a simple solution below.
I wrote a small script to do just this. Feel free to make suggestions and edits. It works by checking if the surface of each sphere falls within the volume of all of the other spheres.
For sphere intersection, it's better (but slower) to use a larger number of faces in the sphere() function call. This should give denser results in the visualization. For the sphere-alone visualization, a smaller number (~50) should suffice. See the comments for how to visualize each.
close all
clear
clc
% centers : 3 x N matrix of [X;Y;Z] coordinates
% dist : 1 x N vector of sphere radii
%% Plot spheres (fewer faces)
figure, hold on % One figure to rule them all
[x,y,z] = sphere(50); % 50x50-face sphere
for i = 1 : size(centers,2)
h = surfl(dist(i) * x + centers(1,i), dist(i) * y + centers(2,i), dist(i) * z + centers(3,i));
set(h, 'FaceAlpha', 0.15)
shading interp
end
%% Plot intersection (more faces)
% Create a 1000x1000-face sphere (bigger number = better visualization)
[x,y,z] = sphere(1000);
% Allocate space
xt = zeros([size(x), size(centers,2)]);
yt = zeros([size(y), size(centers,2)]);
zt = zeros([size(z), size(centers,2)]);
xm = zeros([size(x), size(centers,2), size(centers,2)]);
ym = zeros([size(y), size(centers,2), size(centers,2)]);
zm = zeros([size(z), size(centers,2), size(centers,2)]);
% Calculate each sphere
for i = 1 : size(centers, 2)
xt(:,:,i) = dist(i) * x + centers(1,i);
yt(:,:,i) = dist(i) * y + centers(2,i);
zt(:,:,i) = dist(i) * z + centers(3,i);
end
% Determine whether the points of each sphere fall within another sphere
% Returns booleans
for i = 1 : size(centers, 2)
[xm(:,:,:,i), ym(:,:,:,i), zm(:,:,:,i)] = insphere(xt, yt, zt, centers(1,i), centers(2,i), centers(3,i), dist(i)+0.001);
end
% Exclude values of x,y,z that don't fall in every sphere
xmsum = sum(xm,4);
ymsum = sum(ym,4);
zmsum = sum(zm,4);
xt(xmsum < size(centers,2)) = 0;
yt(ymsum < size(centers,2)) = 0;
zt(zmsum < size(centers,2)) = 0;
% Plot intersection
for i = 1 : size(centers,2)
xp = xt(:,:,i);
yp = yt(:,:,i);
zp = zt(:,:,i);
zp(~(xp & yp & zp)) = NaN;
surf(xt(:,:,i), yt(:,:,i), zp, 'EdgeColor', 'none');
end
and here is the insphere function
function [x_new,y_new,z_new] = insphere(x,y,z, x0, y0, z0, r)
x_new = (x - x0).^2 + (y - y0).^2 + (z - z0).^2 <= r^2;
y_new = (x - x0).^2 + (y - y0).^2 + (z - z0).^2 <= r^2;
z_new = (x - x0).^2 + (y - y0).^2 + (z - z0).^2 <= r^2;
end
Sample visualizations
For the 6 spheres used in these examples, it took an average of 1.934 seconds to run the combined visualization on my laptop.
Intersection of 6 spheres:
Actual 6 spheres:
Below, I've combined the two so you can see the intersection in the view of the spheres.
For these examples:
centers =
-0.0065 -0.3383 -0.1738 -0.2513 -0.2268 -0.3115
1.6521 -5.7721 -1.7783 -3.5578 -2.9894 -5.1412
1.2947 -0.2749 0.6781 0.2438 0.4235 -0.1483
dist =
5.8871 2.5280 2.7109 1.6833 1.9164 2.1231
I hope this helps anyone else who may desire to visualize this effect.

Create random unit vector inside a defined conical region

I'm looking for a simple way for creating a random unit vector constrained by a conical region. The origin is always the [0,0,0].
My solution up to now:
function v = GetRandomVectorInsideCone(coneDir,coneAngleDegree)
coneDir = normc(coneDir);
ang = coneAngleDegree + 1;
while ang > coneAngleDegree
v = [randn(1); randn(1); randn(1)];
v = v + coneDir;
v = normc(v);
ang = atan2(norm(cross(v,coneDir)), dot(v,coneDir))*180/pi;
end
My code loops until the random generated unit vector is inside the defined cone. Is there a better way to do that?
Resultant image from test code bellow
Resultant frequency distribution using Ahmed Fasih code (in comments).
I wonder how to get a rectangular or normal distribution.
c = [1;1;1]; angs = arrayfun(#(i) subspace(c, GetRandomVectorInsideCone(c, 30)), 1:1e5) * 180/pi; figure(); hist(angs, 50);
Testing code:
clearvars; clc; close all;
coneDir = [randn(1); randn(1); randn(1)];
coneDir = [0 0 1]';
coneDir = normc(coneDir);
coneAngle = 45;
N = 1000;
vAngles = zeros(N,1);
vs = zeros(3,N);
for i=1:N
vs(:,i) = GetRandomVectorInsideCone(coneDir,coneAngle);
vAngles(i) = subspace(vs(:,i),coneDir)*180/pi;
end
maxAngle = max(vAngles);
minAngle = min(vAngles);
meanAngle = mean(vAngles);
AngleStd = std(vAngles);
fprintf('v angle\n');
fprintf('Direction: [%.3f %.3f %.3f]^T. Angle: %.2fº\n',coneDir,coneAngle);
fprintf('Min: %.2fº. Max: %.2fº\n',minAngle,maxAngle);
fprintf('Mean: %.2fº\n',meanAngle);
fprintf('Standard Dev: %.2fº\n',AngleStd);
%% Plot
figure;
grid on;
rotate3d on;
axis equal;
axis vis3d;
axis tight;
hold on;
xlabel('X'); ylabel('Y'); zlabel('Z');
% Plot all vectors
p1 = [0 0 0]';
for i=1:N
p2 = vs(:,i);
plot3ex(p1,p2);
end
% Trying to plot the limiting cone, but no success here :(
% k = [0 1];
% [X,Y,Z] = cylinder([0 1 0]');
% testsubject = surf(X,Y,Z);
% set(testsubject,'FaceAlpha',0.5)
% N = 50;
% r = linspace(0, 1, N);
% [X,Y,Z] = cylinder(r, N);
%
% h = surf(X, Y, Z);
%
% rotate(h, [1 1 0], 90);
plot3ex.m:
function p = plot3ex(varargin)
% Plots a line from each p1 to each p2.
% Inputs:
% p1 3xN
% p2 3xN
% args plot3 configuration string
% NOTE: p1 and p2 number of points can range from 1 to N
% but if the number of points are different, one must be 1!
% PVB 2016
p1 = varargin{1};
p2 = varargin{2};
extraArgs = varargin(3:end);
N1 = size(p1,2);
N2 = size(p2,2);
N = N1;
if N1 == 1 && N2 > 1
N = N2;
elseif N1 > 1 && N2 == 1
N = N1
elseif N1 ~= N2
error('if size(p1,2) ~= size(p1,2): size(p1,2) and/or size(p1,2) must be 1 !');
end
for i=1:N
i1 = i;
i2 = i;
if i > N1
i1 = N1;
end
if i > N2
i2 = N2;
end
x = [p1(1,i1) p2(1,i2)];
y = [p1(2,i1) p2(2,i2)];
z = [p1(3,i1) p2(3,i2)];
p = plot3(x,y,z,extraArgs{:});
end
Here’s the solution. It’s based on the wonderful answer at https://math.stackexchange.com/a/205589/81266. I found this answer by googling “random points on spherical cap”, after I learned on Mathworld that a spherical cap is this cut of a 3-sphere with a plane.
Here’s the function:
function r = randSphericalCap(coneAngleDegree, coneDir, N, RNG)
if ~exist('coneDir', 'var') || isempty(coneDir)
coneDir = [0;0;1];
end
if ~exist('N', 'var') || isempty(N)
N = 1;
end
if ~exist('RNG', 'var') || isempty(RNG)
RNG = RandStream.getGlobalStream();
end
coneAngle = coneAngleDegree * pi/180;
% Generate points on the spherical cap around the north pole [1].
% [1] See https://math.stackexchange.com/a/205589/81266
z = RNG.rand(1, N) * (1 - cos(coneAngle)) + cos(coneAngle);
phi = RNG.rand(1, N) * 2 * pi;
x = sqrt(1-z.^2).*cos(phi);
y = sqrt(1-z.^2).*sin(phi);
% If the spherical cap is centered around the north pole, we're done.
if all(coneDir(:) == [0;0;1])
r = [x; y; z];
return;
end
% Find the rotation axis `u` and rotation angle `rot` [1]
u = normc(cross([0;0;1], normc(coneDir)));
rot = acos(dot(normc(coneDir), [0;0;1]));
% Convert rotation axis and angle to 3x3 rotation matrix [2]
% [2] See https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
crossMatrix = #(x,y,z) [0 -z y; z 0 -x; -y x 0];
R = cos(rot) * eye(3) + sin(rot) * crossMatrix(u(1), u(2), u(3)) + (1-cos(rot))*(u * u');
% Rotate [x; y; z] from north pole to `coneDir`.
r = R * [x; y; z];
end
function y = normc(x)
y = bsxfun(#rdivide, x, sqrt(sum(x.^2)));
end
This code just implements joriki’s answer on math.stackexchange, filling in all the details that joriki omitted.
Here’s a script that shows how to use it.
clearvars
coneDir = [1;1;1];
coneAngleDegree = 30;
N = 1e4;
sol = randSphericalCap(coneAngleDegree, coneDir, N);
figure;plot3(sol(1,:), sol(2,:), sol(3,:), 'b.', 0,0,0,'rx');
grid
xlabel('x'); ylabel('y'); zlabel('z')
legend('random points','origin','location','best')
title('Final random points on spherical cap')
Here is a 3D plot of 10'000 points from the 30° spherical cap centered around the [1; 1; 1] vector:
Here’s 120° spherical cap:
Now, if you look at the histogram of the angles between these random points at the coneDir = [1;1;1], you will see that the distribution is skewed. Here’s the distribution:
Code to generate this:
normc = #(x) bsxfun(#rdivide, x, sqrt(sum(x.^2)));
mysubspace = #(a,b) real(acos(sum(bsxfun(#times, normc(a), normc(b)))));
angs = arrayfun(#(i) mysubspace(coneDir, sol(:,i)), 1:N) * 180/pi;
nBins = 16;
[n, edges] = histcounts(angs, nBins);
centers = diff(edges(1:2))*[0:(length(n)-1)] + mean(edges(1:2));
figure('color','white');
bar(centers, n);
xlabel('Angle (degrees)')
ylabel('Frequency')
title(sprintf('Histogram of angles between coneDir and random points: %d deg', coneAngleDegree))
Well, this makes sense! If you generate points from the 120° spherical cap around coneDir, of course the 1° cap is going to have very few of those samples, whereas the strip between the 10° and 11° caps will have far more points. So what we want to do is normalize the number of points at a given angle by the surface area of the spherical cap at that angle.
Here’s a function that gives us the surface area of the spherical cap with radius R and angle in radians theta (equation 16 on Mathworld’s spherical cap article):
rThetaToH = #(R, theta) R * (1 - cos(theta));
rThetaToS = #(R, theta) 2 * pi * R * rThetaToH(R, theta);
Then, we can normalize the histogram count for each bin (n above) by the difference in surface area of the spherical caps at the bin’s edges:
figure('color','white');
bar(centers, n ./ diff(rThetaToS(1, edges * pi/180)))
The figure:
This tells us “the number of random vectors divided by the surface area of the spherical segment between histogram bin edges”. This is uniform!
(N.B. If you do this normalized histogram for the vectors generated by your original code, using rejection sampling, the same holds: the normalized histogram is uniform. It’s just that rejection sampling is expensive compared to this.)
(N.B. 2: note that the naive way of picking random points on a sphere—by first generating azimuth/elevation angles and then converting these spherical coordinates to Cartesian coordinates—is no good because it bunches points near the poles: Mathworld, example, example 2. One way to pick points on the entire sphere is sampling from the 3D normal distribution: that way you won’t get bunching near poles. So I believe that your original technique is perfectly appropriate, giving you nice, evenly-distributed points on the sphere without any bunching. This algorithm described above also does the “right thing” and should avoid bunching. Carefully evaluate any proposed algorithms to ensure that the bunching-near-poles problem is avoided.)
it is better to use spherical coordinates and convert it to cartesian coordinates:
coneDirtheta = rand(1) * 2 * pi;
coneDirphi = rand(1) * pi;
coneAngle = 45;
N = 1000;
%perfom transformation preventing concentration of points around the pole
rpolar = acos(cos(coneAngle/2*pi/180) + (1-cos(coneAngle/2*pi/180)) * rand(N, 1));
thetapolar = rand(N,1) * 2 * pi;
x0 = rpolar .* cos(thetapolar);
y0 = rpolar .* sin(thetapolar);
theta = coneDirtheta + x0;
phi = coneDirphi + y0;
r = rand(N, 1);
x = r .* cos(theta) .* sin(phi);
y = r .* sin(theta) .* sin(phi);
z = r .* cos(phi);
scatter3(x,y,z)
if all points should be of length 1 set r = ones(N,1);
Edit:
since intersection of cone with sphere forms a circle first we create random points inside a circle with raduis of (45 / 2) in polar coordinates and as #Ahmed Fasih commented to prevent concentration of points near the pole we should first transform this random points, then convert polar to cartesian 2D coordinates to form x0 and y0
we can use x0 and y0 as phi & theta angle of spherical coordinates and add coneDirtheta & coneDirphi as offsets to these coordinates.
then convert spherical to cartesian 3D coordinates

How to generate random positions with distance between them inside the hexagon?

I am trying to create N random pairs of points (N = 50) of a given distances, inside a 500 meters hexagon. The distance D created by using (dmax - dmin).*rand(N,1) + dmin, with dmin = 10 and dmax = 100 in Matlab. I understant that the first I have to generate a set of points ([x1 y1]) that have at least distance D from the main hexagon border, then generate the second set of points ([x2 y2]) that have exact distance D from the first set. But sometime I got the problem with the second point outside of hexagon, because if the first position on the hexagol border and plus Ddisance, then the second position is outside of hexagon (I mean that I want to generate random pair position inside of hexagol). Could anybody help me in generating this kind of scenario and fix the problem? Thanks.
For example as
R = 500; % hexagol radius
N = 50; % number pair positions
d_min = 10; % minimum distance
d_max = 100; % maximum distance
D = (d_max - d_min).*rand(N,1) + d_min; % randomly distance
X = [0,0]; % hexagol center
j=0;
while j < N
j=j+1;
theta(j)=2*pi*rand(1,1);
u= rand()+ rand();
if u < 1
r(j) = R * u;
else
r(j) = R * (2 - u);
end
% to create the first position
x1(j)=r(j)*cos(theta(j)) + X(1,1); % first x positions
y1(j)=r(j)*sin(theta(j)) + X(1,2); % first y positions
end
% to create the second position
x2(j) = x1(j) + D(j); % second x positions
y2(j) = y1(j) + D(j); % second y positions
This is quite like your other question and its solution is almost the same, but it needs a little more math. Let’s focus on one pair of points. There still are two steps:
Step 1: Find a random point that is inside the hexagon, and has distance d from its border.
Step 2: Find another point that has distance d from first point.
Main problem is step 1. We can say that a points that has distance d form a hexagon with radius r, is actually inside a hexagon with radius r-d. Then we just need to find a random point that lays on a hexagon!
Polar Formula of Hexagons:
I want to solve this problem in polar space, so I have to formulate hexagons in this space. Remember circle formula in polar space:
The formula of a hexagon in polar space is pretty much like its circumscribe circle, except that the radius of the hexagon differs at every t (angle). Let’s call this changing radius r2. So, if we find the function R2 that returns r2 for all ts then we can write polar formula for hexagon:
This image demonstrates parameters of the problem:
The key parameter here is α. Now we need a function Alpha that returns α for all ts:
Now we have all points on border of the hexagon in polar space:
r = 500;
T = linspace(0, 2*pi, 181);
Alpha = #(t) pi/2-abs(rem(t, pi/3)-(pi/6));
R2 = #(t) r*cos(pi/6)./sin(Alpha(t));
X = R2(T).*cos(T);
Y = R2(T).*sin(T);
hold on
plot(X, Y, '.b');
plot((r).*cos(T), (r).*sin(T), '.r')
Polar Formula of a Regular Polygon:
Before I go on I’d like to generalize Alpha and R2 functions to cover all regular polygons:
Alpha = #(t) pi/2-abs(rem(t, 2*pi/(n))-(pi/(n)));
R2 = #(t) r*cos(pi/n)./sin(Alpha(t));
Where n is the number of edges of the polygon.
Answer:
Now we can generate pairs of points just like what we did for the circle problem:
r = 500; n = 6;
a = 10; b = 50;
N = 100;
D = (b - a).*rand(N,1) + a;
Alpha = #(t) pi/2-abs(rem(t, 2*pi/(n))-(pi/(n)));
R2 = #(t) r*cos(pi/n)./sin(Alpha(t));
T1 = rand(N, 1) * 2 * pi;
RT1 = rand(N, 1) .* (R2(T1)-D);
X1 = RT1.*cos(T1);
Y1 = RT1.*sin(T1);
T2 = rand(N, 1) * 2 * pi;
X2 = X1+D.*cos(T2);
Y2 = Y1+D.*sin(T2);
Rotating the polygon:
For rotating the polygon we just need to update the Alpha function:
t0 = pi/8;
Alpha = #(t) pi/2-abs(rem(t+t0, 2*pi/(n))-(pi/(n)));
This is a test for n=7, N=50000 and t0=pi/10:

How to draw tangent line at specified points in a curve in Matlab

I am having a an array of points x,y and respective angles at those specified points. I want to plot a tangent line at those points, i am unable to figure out how to proceed.
http://postimg.org/image/s2y1pqqaj/
As shown in command window 1st column contains x points , 2nd column contains y points and 3rd column the respective tangent angle. Figure 1 is plot between x and y points.
I know the slope i.e tangent angle at every point as you can see it in the 3rd column. But not able to understand how to implement it to draw tangent at these points . Also the equation for tangent line 'y = mx + b' where m - slope and b is y intercept. Thanking you.
Here is the code
% Fill in parr a list of points and tangents to be used for display.
% #param parr (x,y) Array of points.
% #param tan Array of tangents.
% #param lengthStep Distance between points.
function [x y tan] = GetPointListForDisplay(m_Length,r1,r2,count)
global nn ca ce length;
GetLength = m_Length;
length = GetLength;
ca = GetCurvatureAtDeltaLength(0.0);
ce = GetCurvatureAtDeltaLength(length);
%if ((abs(ca) < 1.0/10000.0) && (abs(ce) < 1.0/10000.0))
%end
radius = 1.0 ./ max(abs(ca), abs(ce));
%if (radius < 0.1)
%end
nn = 3 + (180.0 * length/(2*pi*radius)); % Using modified formula of arc here
lengthStep = length/nn;
currLen = -lengthStep;
while (1)
currLen = currLen + lengthStep;
if (currLen > m_Length)
currLen = m_Length;
end
[x,y] = GetPointAtDeltaLength(currLen);
[tan] = GetTangentGridBearingAtDeltaLength(currLen);
z(count,1) = x;
z(count,2)= y;
z(count,3)= tan;
figure(1);
%plot(z(count,1).*sin(z(count,3)),z(count,2).*cos(z(count,3)),'b*');
%plot(z(1,count).*cos(z(3,count)),z(2,count).*sin(z(3,count)),'b*');
plot(z(count,1),z(count,2),'b*');
%plot(z(1,count),z(2,count),'b*');
hold on;
%pause(0.1);
count=count+1;
axis equal;
if (currLen >= m_Length)
z(count,1)= tan
break;
end
end
end
Regards,
Mrinal
ii = index of the point where you want to get the tangent
x1 = left bound of your tangent
x2 = right bound of your tangent
xT = z(ii,1) %argument where you want to get the tangent
yT = z(ii,2) %corresponding y
mT = tan(z(ii,3)) % corresponding slope
I assume you just want one tangent, then plot it like this.
plot( [x1,xT,x2] , [yT-mT*(xT-x1), yT, yT+mT*(x2-xT)] )
Otherwise just use a loop for more tangents using ii as iteration variable.
The string for your equation would be
eq = strcat('y = ',num2str(mT),'*x + ',num2str(yT-mT*xT))