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

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:

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

Finding the values of a scalar function on a 3D grid which correspond to the direction of slowest increase

I have some scalar function F(x,y,z) defined on a grid in 3D space, and there is a minimum of F somewhere in the array. Example code to generate such a function, and locate the coordinates of the minimum, is given below:
x = linspace(-10,80,100);
y = linspace(-20,5,100);
z = linspace(-10,10,100);
[X,Y,Z] = meshgrid(x,y,z);
F = some_scalar_function(X, Y, Z);
% Find the minimum of the function on the grid
[minval,ind] = min(F(:));
[ii,jj,kk] = ind2sub(size(F),ind);
xmin = x(jj);
ymin = y(ii);
zmin = z(kk);
figure;isosurface(X,Y,Z,F,minval+100)
% Some sample scalar function (assume it is given on the grid, and the analytic form not known)
function F = some_scalar_function(X, Y, Z)
F = (X-6).^2 + 10*(Y+2).^2 + 10*Z.^2 + 5*X.*Y;
end
I would like to obtain a vector of F values from the grid along some new direction (let's call it r) which corresponds to the direction of slowest increase of the function F, i.e starting from the minimum and "walking" outwards. I would also like to obtain the corresponding values of the coordinate r as well. I have tried to explain what I mean in the figure below:
Taking a path along any direction other than r should lead to a steeper increase in F, and is therefore not the correct route. Can anyone show how this can be done in Matlab? Thanks!
EDIT
After the comments from rahnema1 and Ander Biguri, I have run the command
[Gmag,Gazimuth,Gelevation] = imgradient3(F);
Taking a look at a plane through z=0, the function F(x,y,z=0) itself looks like the following:
and the outputs from imgradient3() look like this (again, only a single plane from the resulting full 3D arrays):
How can I obtain the line cut corresponding to path of slowest increase as a function of r from these? (still bearing in mind they are 3D arrays, and the direction is not necessarily constrained to the z=0 plane).
Consider a sphere that its center is the position of the minimum point of F.
For each point on the surface of the sphere compute the shortest path to the center point. use imerode to find the surface of the sphere and use shortestpathtree to compute the tree of shortest paths.
Gradient magnitude is set as the difficulty of path traversal. Use imgradient3 to calculate the gradient magnitude.
The path between the surface point with the minimum distance to the center , path1, is considered the direction of slowest increase of the function F.
But path1 is the half of the path. Other half ,path2, is computed by eliminating the sub-tree that contains the first surface point and again computing the shortest path tree using the resulting graph. The function im2col3 is defined for converting the 3D array to graph data structure.
Here is the non tested code:
% im2col for 3D image
function col = im2col3 (im)
col = zeros(prod(size(im)-2), 26);
n = 1;
for kk = 1:3
for jj = 1:3
for ii = 1:3
if ~(ii == 2 && jj == 2 && kk == 2)
col(:, n) = reshape(im(ii:end-(3-ii), jj:end-(3-jj), kk:end-(3-kk)),[],1);
n = n + 1;
end
end
end
end
end
% gradient magnitude
[Gmag,~,~] = imgradient3(F);
% convert array to graph
idx = reshape(1:numel(F), size(F));
t = im2col3(idx);
w = Gmag(t);
s = repmat(reshape(idx(2:end-1,2:end-1,2:end-1),[],1), size(t, 2));
G = graph(s, t, w);
% form the sphere
[~, sphere_center] = min(F(:));
[r, c, z] = ind2sub(size(F), sphere_center);
sphere_radius_2 = min([r c z]) ^ 2;
sphere_logical = ((1:size(F, 1)).'- r) .^ 2 ...
+ ((1:size(F, 2))- c) .^ 2 ...
+ (reshape(1:size(F, 3), 1, 1, [])- z) .^ 2 ...
< sphere_radius_2;
se = strel('cube',3);
sphere_surface = xor(imerode(sphere_logical, se), sphere_logical);
sphere_nodes = idx(sphere_surface);
% compute the half of the path
[T, D] = shortestpathtree(G, sphere_center, sphere_nodes,'OutputForm','cell');
[mn1, im1] = min(D);
path1 = T{im1};
% eliminate the sub-tree
subtree_root = path1(2);
subtree_nodes = bfsearch(T, subtree_root);
G1 = rmnodes (G, subtree_nodes);
sphere_nodes = setdiff (sphere_nodes, subtree_nodes);
% computing other half
[T1, D1] = shortestpathtree(G1, sphere_center, sphere_nodes,'OutputForm','cell');
[mn2, im2] = min(D1);
path2 = T1{im2};

Points distribution in n-dimension

How to distribute the points to be like Fig.A
This matlab code for Fig. B :
N = 30; % number of points
r = 0.5; % r = radius
d = 50; % dimension
C_point = 0; % center point
figure, clf
C = ones(1, d) * C_point;
C_rep = repmat( C,N,1);
X = randn(N,d);
s2 = sum(X.^2,2) ;
radius = r * (rand(N,1).^(1/d));
X = X.*repmat(radius./sqrt(s2),1,d) + C_rep;
%% Plot 2D
t = linspace(0, 2*pi, 100);
x = r*cos(t) + C(1);
y = r*sin(t) + C(2);
plot(x,y,'b')
hold on
plot(C(1),C(2),'b.', 'MarkerSize', 10) % center point
hold on
plot(X(:,1), X(:,2),'r.','markersize',10);
axis equal;rotate3d off; rotate3d on;drawnow;shg;
hold on
ax = axis;
Source of the code
What I should change to be like fig. A
The OP's code computes points uniformly distributed within a d-dimensional box, projects those onto a d-dimensional sphere, then samples the radius to move them inside the d-dimensional ball. This is perfect except that the points inside the box, when projected onto the sphere, do not form a uniform distribution on that sphere. If instead you find random points distributed in a Gaussian distribution, you are guaranteed uniform angle distribution.
First compute points with a Gaussian distribution in d dimensions (I do all here with minimal changes to the OP's code):
N = 1000; % number of points
r = 0.5; % r = radius
d = 3; % dimension
C_point = 0; % center point
C = ones(1,d) * C_point;
C_rep = repmat(C,N,1);
X = randn(N,d);
Note that I use randn, not rand. randn creates a Gaussian distribution.
Next we normalize the vectors so the points move to the sphere:
nX = sqrt(sum(X.^2,2));
X = X./repmat(nX,1,d);
These points are uniformly distributed, which you can verify by scatter3(X(:,1),X(:,2),X(:,3)); axis equal and turning the display around (a 2D rendering doesn't do it justice). This is the reason I set d=3 above, and N=1000. I wanted to be able to plot the points and see lots of them.
Next we compute, as you already did, a random distance to the origin, and correct it for the dimensionality:
radius = r * (rand(N,1).^(1/d));
X = X.*repmat(radius,1,d) + C_rep;
X now is distributed uniformly in the ball. Again, scatter3(X(:,1),X(:,2),X(:,3)); axis equal shows this.
However, if you set d=50 and then plot only two dimensions of your data, you will not see the data filling the circle. And you will not see a uniform distribution either. This is because you are projecting a 50-D ball onto 2 dimensions, this simply does not work. You either have to trust the math, or you have to slice the data:
figure, hold on
t = linspace(0, 2*pi, 100);
x = r*cos(t) + C(1);
y = r*sin(t) + C(2);
plot(x,y,'b')
plot(C(1),C(2),'b.', 'MarkerSize', 10) % center point
axis equal
I = all(abs(X(:,3:d))<0.1,2);
plot(X(I,1), X(I,2),'r.','markersize',10);
The I there indexes points that are close to the origin in dimensions perpendicular to the first two shown. Again, with d=50 you will have very few points there, so you will need to set N very large! To see the same density of points as in the case above, for every dimension you add, you need to multiply N by 10. So for d=5 you'd have N=1000*10*10=1e5, and for d=50 you'd need N=1e50. That is totally impossible to compute, of course.

Divide Mesh grid by a bisector, MATLAB

I have a piecewise function, where domain changes for each case. The function is as follows:
For
(x,y)greater than Divider v= f(x,y) (A1)
(x,y)less than Divider v = g(x,y) (A2)
The location of the divider changes with tilt angle of the rectangle given in figures 1 and 2.Figure 1 & 2 The divider will always be a bisector of the rectangle. For example, the divider makes an angle (alpha + 90) with the horizontal.
If the rectangle makes an angle 0, it's easy to implement above functions as I can create meshgrid from
x =B to C & y = A to D for A1
x =A to B & y = A to D for A2
However, when the angles for the rectangle are different, I can't figure out how to create the mesh to calculate the function v using the algorithm A1 and A2 above.
I was thinking of using some inequality and using the equation of the line (as I have the co-ordinates for the center of the rectangle and the angle of tilt). But, I can't seem to think of a way to do it for all angles (for example , slope of pi/2 as in the first figure, yields infinity). Even if I do create some kind of inequality, I can't create a mesh.
1Please help me with this problem. I have wasted a lot of time on this. It seems to be out of my reach
%% Constants
Angle1=0;
Angle1=Angle1.*pi./180;
rect_center=0; % in m
rect_length=5; % in m
rect_width=1; % in m
rect_strength=1.8401e-06;
Angle2=0;
Angle2 =Angle2.*pi./180;
%% This code calculates the outer coordinates of the rectangle by using the central point
% the following code calculates the vertices
vertexA=rect_center+(-rect_width./2.*exp(1i.*1.5708)-rect_length./2).*exp(1i.*Angle2);
vertexA=[vertexA,vertexA+2.*(rect_width./2.*exp(1i.*1.5708)).*exp(1i.*Angle2)];
vertexB=rect_center+(-rect_width./2.*exp(1i.*1.5708)+rect_length./2).*exp(1i.*Angle2);
vertexB=[vertexB,vertexB+2.*(rect_width./2.*exp(1i.*1.5708)).*exp(1i.*Angle2)];
za1=vertexA(1:numel(vertexA)/2);
za2=vertexA(1+numel(vertexA)/2:numel(vertexA));
zb1=vertexB(1:numel(vertexB)/2);
zb2=vertexB(1+numel(vertexB)/2:numel(vertexB));
arg1=exp(-1i.*Angle2);
%% This Section makes the two equations necessary for making the graphs
syms var_z
% Equation 1
Eqn1(var_z)=1.5844e-07.*exp(-1i.*Angle1).*var_z./9.8692e-13;
% subparts of the Equation 2
A = 1.0133e+12.*(-1i.*rect_strength.*exp(-1i*Angle2)./(2*pi.*rect_length.*rect_width*0.2));
ZA1 = var_z+za1-2*rect_center;
ZA2 = var_z+za2-2*rect_center;
ZB1 = var_z+zb1-2*rect_center;
ZB2 = var_z+zb2-2*rect_center;
ZAA2 = log(abs(ZA2)) + 1i*mod(angle(ZA2),2*pi);
ZAA1 = log(abs(ZA1)) + 1i*mod(angle(ZA1),2*pi);
ZBB1 = log(abs(ZB1)) + 1i*mod(angle(ZB1),2*pi);
ZBB2 = log(abs(ZB2)) + 1i*mod(angle(ZB2),2*pi);
%Equation 2 ; this is used for the left side of the center
Eqn2= A*(ZA2*(log(ZA2)-1)-(ZA1*(log(ZA1)-1))+(ZB1*(log(ZB1)-1))-(ZB2*(log(ZB2)-1)));
%Equation 3 ; this is used for the right side of the center
Eqn3 = A.*(ZA2*(ZAA2-1)-(ZA1*(ZAA1-1))+(ZB1*(ZBB1-1))-(ZB2*(ZBB2-1)));
%Equation 4 :Add Equation 2 and Equation 1; this is used for the left side of the center
Eqn4 = matlabFunction(Eqn1+Eqn2,'vars',var_z);
%Equation 5: Add Equation 3 and Equation 1; this is used for the right side of the center
Eqn5 = matlabFunction(Eqn1+Eqn3,'vars',var_z);
%% Prepare for making the plots
minx=-10; %min x coordinate
maxx=10; %max x coordinate
nr_x=1000; %nr x points
miny=-10; %min y coordinate
maxy=10; %max y coordinate
nr_y=1000; %nr y points
%This vector starts from left corner (minx) to the middle of the plot surface,
%The middle of the plot surface lies at the center of the rectange
%created earlier
xvec1=minx:(rect_center-minx)/(0.5*nr_x-1):rect_center;
%This vector starts from middle to the right corner (maxx) of the plot surface,
%The middle of the plot surface lies at the center of the rectange
%created earlier
xvec2=rect_center:(maxx-rect_center)/(0.5*nr_x-1):maxx;
%the y vectors start from miny to maxy
yvec1=miny:(maxy-miny)/(nr_y-1):maxy;
yvec2=miny:(maxy-miny)/(nr_y-1):maxy;
% create mesh from above vectors
[x1,y1]=meshgrid(xvec1,yvec1);
[x2,y2]=meshgrid(xvec2,yvec2);
z1=x1+1i*y1;
z2=x2+1i*y2;
% Calculate the above function using equation 4 and equation 5 using the mesh created above
r1 = -real(Eqn5(z1));
r2 = -real(Eqn4(z2));
%Combine the calculated functions
Result = [r1 r2];
%Combine the grids
x = [x1 x2];
y = [y1 y2];
% plot contours
[c,h]=contourf(x,y,Result(:,:,1),50,'LineWidth',1);
% plot the outerboundary of the rectangle
line_x=real([vertexA;vertexB]);
line_y=imag([vertexA;vertexB]);
line(line_x,line_y,'color','r','linestyle',':','linewidth',5)
The final Figure is supposed to look like this.Final Expected Figure.
I'm not sure which angle defines the dividing line so I assume it's Angle1. It looks like logical indexing is the way to go here. Instead of creating two separate mesh grids we simply create the entire mesh grid then partition it into two sets and operate on each independently.
%% Prepare for making the plots
minx=-10; %min x coordinate
maxx=10; %max x coordinate
nr_x=1000; %nr x points
miny=-10; %min y coordinate
maxy=10; %max y coordinate
nr_y=1000; %nr y points
% create full mesh grid
xvec=linspace(minx,maxx,nr_x);
yvec=linspace(miny,maxy,nr_y);
[x,y]=meshgrid(xvec,yvec);
% Partition mesh based on divider line
% Assumes the line passes through (ox,oy) with normal vector defined by Angle1
ox = rect_center;
oy = rect_center;
a = cos(Angle1);
b = sin(Angle1);
c = -(a*ox + b*oy);
% use logical indexing to opperate on the appropriate parts of the mesh
idx1 = a*x + b*y + c < 0;
idx2 = ~idx1;
z = zeros(size(x));
z(idx1) = x(idx1) + 1i*y(idx1);
z(idx2) = x(idx2) + 1i*y(idx2);
% Calculate the above function using equation 4 and equation 5
% using the mesh created above
Result = zeros(size(z));
Result(idx1) = -real(Eqn5(z(idx1)));
Result(idx2) = -real(Eqn4(z(idx2)));
For example with Angle1 = 45 and Angle2 = 45 we get the following indexing
>> contourf(x,y,idx1);
>> line(line_x,line_y,'color','r','linestyle',':','linewidth',5);
where the yellow region uses Eqn5 and the blue region uses Eqn4. This agrees with the example you posted but I don't know what the resulting contour map for other cases is supposed to look like.
Hope this helps.

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))