Intersection point of two independet lines in MATLAB - matlab

I am writing a code to find the intersection point value of two independent lines , but I am confused that how to obtain the value of the intersection point , till now I have coded :
y = [2.63 8.12 13.01 21.87 35.19 58.49];
x = [200 400 500 600 800 1000];
plot(x,y)
hold on
plot([200, 1000], [10, 10]) % this [10, 10] is a straight line
hold off
I want to find the meeting point of plot(x,y) and Straight line , Can anyone give me hint for this Thanks :)

The x-coordinate at which the monotonically increasing piecewise linear curve plot(x,y) crosses v is given by:
interp1q(y,x,v);

Ok, this is the formula JakubT was assuming for:
yIntersect = 10;
dy = diff(y);
dx = diff(x);
i=find(diff(y > yIntersect));
xIntersect = x(i)+dx(i)*(yIntersect-y(i))/dy(i);
-->
xIntersect = 438.45
Of course this is not production code.

Not a very elegant solution, but you could, for each pair of consecutive elements of x and y (e.g., [8.12 13.01] and [400 500] being the second such pair), take the equation of the line passing through these two points, compute intersection with your crossing line (I assume that you have/can get the analytical formula for that one?) - and for each such pair of points, you check if the intersection actually happens between these two boundary points - if so, you have both the equation of the line passing through these two points as well as the equation of the crossing line, which yields the point of intersection.

Related

repmat function in Matlab does not work consistently?

Matlab functions meshgrid and streamline are not matching. How to fix?
%% direction field plot
[x,y]=meshgrid(-4:.5:4,-4:.5:4);
dx = 2*x +1*y;
dy = 1*x +2*y;
dxu = dx./sqrt(dx.^2+dy.^2);
dyu = dy./sqrt(dx.^2+dy.^2);
quiver(x,y,dxu,dyu)
hold on
%% Trajectory Plot
startx = repmat([-4:.5:4], 0,2);
starty = ones(size(startx));
streamline(x,y,dxu, dyu, startx, starty)
dxu = dx./sqrt(dx.^2+dy.^2);
dyu = dy./sqrt(dx.^2+dy.^2);
print('c:\data\DirectionField','-dmeta')
saveas(gcf, 'c:\data\streamline.emf')
hold off
Error messages are given below:
Error using repmat!
Replication factors must be a row vector of integers or integer scalars.
This has occurred when I added 7 trajectory plots to the code. When using only two trajectories the error did not occur? What is happening here?
MM
Your startx and starty matrices are currently empty. The last two arguments of repmat should be the number of times you want to repeat the matrix in the vertical and horizontal directions respectively. Since your replication factors are 0 and 2, the result is an empty matrix. Use positive integers for the replication factors.
I'm not completely sure what you're trying to do, but if you want the quiver and streamline plots to be consistent, I think you should not be using repmat at all. Instead, I think you should just do:
streamline(x, y, dxu, dyu, x, y);
Updated after OP's comment:
If you want to want to plot trajectories from a specific set of starting points, use the code below where startxy is an m x 2 matrix containing the coordinates of m starting points.
startxy = [0,2;
1,-3;
2,1]; %e.g. 3 starting points
streamline(x,y,dxu, dyu, startxy(:,1), startxy(:,2));

What is wrong with my lagrange multiplier matlab code?

I want to find the two farthest points lying on a closed curve with respect to a line. Lagrange multiplier seems to be do the job. But something is wrong with my code: I have 10 solution points (length(xsol)=10, some are repeated so the picture has only 7) and only two of them are what I want (with red ticks). Why would some points not lie on the curve?
syms x y L
g = #(x,y) x^2+2*x*y^2+y^6-1;
h = #(x,y) -4*x+y; % to max or min this such that g=0 is satisfied
gradg = jacobian(g,[x,y]); gradh = jacobian(h,[x,y]);
lagr = gradh - L*gradg;
[L,xsol,ysol]=solve(lagr(1),lagr(2),g);
plot(xsol,ysol,'bo')
What is wrong?
Lagrange multiplier gives local max, local min and also complex solutions. To get the farthest two points, we need one more step: evaluate the function values of all the 'solutions', find the indices with respect to the maximum and the minimum and finally we have the two points.
xsolreal=real(double(xsol)); % take the real part for giving accurate results
ysolreal=real(double(ysol));
fnvalue=zeros(1,length(xsol));
for i=1:length(xsol)
fnvalue(i)=-4*xsolreal(i)+ysolreal(i); % function value of the given line
end
gmax=find(fnvalue == max(fnvalue(:)));
gmin=find(fnvalue == min(fnvalue(:)));
x1=xsolreal(gmax);
y1=ysolreal(gmax);
x2=xsolreal(gmin);
y2=ysolreal(gmin);

How to find the intersection of two ellipses in MATLAB

I have two equations:
ellipseOne = '((x-1)^2)/6^2 + y^2/3^2 = 1';
and
ellipseTwo = '((x+2)^2)/2^2 + ((y-5)^2)/4^2 = 1';
and I plotted them:
ezplot(ellipseOne, [-10, 10, -10, 10])
hold on
ezplot(ellipseTwo, [-10, 10, -10, 10])
title('Ellipses')
hold off
Now I'm trying to find the intersection of the two ellipses. I tried:
intersection = solve(ellipseOne, ellipseTwo)
intersection.x
intersection.y
to find the points where they intersect, but MATLAB is giving me a matrix and an equation as an answer which I don't understand. Could anyone point me in the right direction to get the coordinates of intersection?
The solution is in symbolic form. The last step you need to take is to transform it into numeric. Simply convert the result using double. However, because this is a pair of quadratic equations, there are 4 possible solutions due to the sign ambiguity (i.e. +/-) and can possibly give imaginary roots. Therefore, isolate out the real solutions and what is left should be your answer.
Therefore:
% Your code
ellipseOne = '((x-1)^2)/6^2 + y^2/3^2 = 1';
ellipseTwo = '((x+2)^2)/2^2 + ((y-5)^2)/4^2 = 1';
intersection = solve(ellipseOne, ellipseTwo);
% Find the points of intersection
X = double(intersection.x);
Y = double(intersection.y);
mask = ~any(imag(X), 2) | ~any(imag(Y), 2);
X = X(mask); Y = Y(mask);
The first three lines of code are what you did. The next four lines extract out the roots in numeric form, then I create a logical mask that isolates out only the points that are real. This looks at the imaginary portion of both the X and Y coordinate of all of the roots and if there is such a component for any of the roots, we want to eliminate those. We finally remove the roots that are imaginary and we should be left with two real roots.
We thus get for our intersection points:
>> disp([X Y])
-3.3574 2.0623
-0.2886 2.9300
The first column is the X coordinate and the second column is the Y coordinate. This also seems to agree with the plot. I'll take your ellipse plotting code and also insert the intersection points as blue dots using the above solution:
ezplot(ellipseOne, [-10, 10, -10, 10])
hold on
ezplot(ellipseTwo, [-10, 10, -10, 10])
% New - place intersection points
plot(X, Y, 'b.');
title('Ellipses');
hold off;

Plotting a linear decision boundary

I have a set of data points (40 x 2), and I've derived the formula for the decision boundary which ends up like this :
wk*X + w0 = 0
wk is a 1 x 2 vector and X is a 2 x 1 point from the data point set; essentially X = (xi,yi), where i = 1,2,...,40. I have the values for wk and w0.
I'm trying to plot the line wk*X + w0 = 0 but I have no idea how to plot the actual line. In the past, I've done this by finding the minimum and maximum of the data points and just connecting them together but that's definitely not the right approach.
wk*X is simply the dot product between two vectors, and so the equation becomes:
w1*x + w2*y + w0 = 0
... assuming a general point (x,y). If we rearrange this equation and solve for y, we get:
y = -(w1/w2)*x - (w0/w2)
As such, this defines an equation of the line where the slope is -(w1/w2) with an intercept -(w0/w2). All you have to do is define a bunch of linearly spaced points within a certain range, take each point and substitute this into the above equation and get an output. You'd plot all of these output points in the figure as well as the actual points themselves. You make the space or resolution between points small enough so that we are visualizing a line when we connect all of the points together.
To determine the range or limits of this line, figure out what the smallest and largest x value is in your data, define a set of linearly spaced points between these and plot your line using the equation of the line we just talked about.
Something like this could work assuming that you have a matrix of points stored in X as you have mentioned, and w1 and w2 are defined in the vector wk and w0 is defined separately:
x = linspace(min(X(:,1)), max(X(:,1)));
y = -(wk(1)/wk(2))*x - (w0/wk(2));
plot(X(:,1), X(:,2), 'b.', x, y);
linspace determines a linearly spaced array of points from a beginning to an end, and by default 100 points are generated. We then create the output values of the line given these points and we plot the individual points in blue as well as the line itself on top of these points.

Sequential connecting points in 2D in Matlab

I was wondering if you could advise me how I can connect several points together exactly one after each other.
Assume:
data =
x y
------------------
591.2990 532.5188
597.8405 558.6672
600.0210 542.3244
606.5624 566.2938
612.0136 546.6825
616.3746 570.6519
617.4648 580.4575
619.6453 600.0688
629.4575 557.5777
630.5477 584.8156
630.5477 618.5906
639.2696 604.4269
643.6306 638.2019
646.9013 620.7697
652.3525 601.1584
"data" is coordinate of points.
Now, I would like to connect(plot) first point(1st array) to second point, second point to third point and so on.
Please mind that plot(data(:,1),data(:,2)) will give me the same result. However, I am looking for a loop which connect (plot) each pair of point per each loop.
For example:
data1=data;
figure
scatter(X,Y,'.')
hold on
for i=1:size(data,1)
[Liaa,Locbb] = ismember(data(i,:),data1,'rows');
data1(Locbb,:)=[];
[n,d] = knnsearch(data1,data(i,:),'k',1);
x=[data(i,1) data1(n,1)];
y=[data(i,2) data1(n,2)];
plot(x,y);
end
hold off
Although, the proposed loop looks fine, I want a kind of plot which each point connect to maximum 2 other points (as I said like plot(x,y))
Any help would be greatly appreciated!
Thanks for all of your helps, finally a solution is found:
n=1;
pt1=[data(n,1), data(n,2)];
figure
scatter(data(:,1),data(:,2))
hold on
for i=1:size(data,1)
if isempty(pt1)~=1
[Liaa,Locbb] = ismember(pt1(:)',data,'rows');
if Locbb~=0
data(Locbb,:)=[];
[n,d] = knnsearch(data,pt1(:)','k',1);
x=[pt1(1,1) data(n,1)];
y=[pt1(1,2) data(n,2)];
pt1=[data(n,1), data(n,2)];
plot(x,y);
end
end
end
hold off
BTW it is possible to delete the last longest line as it is not related to the question, if someone need it please let me know.
You don't need to use a loop at all. You can use interp1. Specify your x and y data points as control points. After, you can specify a finer set of points from the first x value to the last x value. You can specify a linear spline as this is what you want to accomplish if the behaviour you want is the same as plot. Assuming that data is a 2D matrix as you have shown above, without further ado:
%// Get the minimum and maximum x-values
xMin = min(data(:,1));
xMax = max(data(:,1));
N = 3000; % // Specify total number of points
%// Create an array of N points that linearly span from xMin to xMax
%// Make N larger for finer resolution
xPoints = linspace(xMin, xMax, N);
%//Use the data matrix as control points, then xPoints are the values
%//along the x-axis that will help us draw our lines. yPoints will be
%//the output on the y-axis
yPoints = interp1(data(:,1), data(:,2), xPoints, 'linear');
%// Plot the control points as well as the interpolated points
plot(data(:,1), data(:,2), 'rx', 'MarkerSize', 12);
hold on;
plot(xPoints, yPoints, 'b.');
Warning: You have two x values that map to 630.5477 but produce different y values. If you use interp1, this will give you an error, which is why I had to slightly perturb one of the values by a small amount to get this to work. This should hopefully not be the case when you start using your own data. This is the plot I get:
You'll see that there is a huge gap between those two points I talked about. This is the only limitation to interp1 as it assumes that the x values are strictly monotonically increasing. As such, you can't have the same two points in your set of x values.