Show the intersection of two curves - matlab

If I have two plots defined by two different equations:
x = 0:0.01:30;
y1 = x .^2 + 2;
y2 = x .^3 ;
and I plot them as
plot(x, y1, x, y2);
How do I get a small ring around the point of intersection programatically (as in the following plot)?

You'll have to find the point of intersection (px, py) manually:
idx = find(y1 - y2 < eps, 1); %// Index of coordinate in array
px = x(idx);
py = y1(idx);
Remember that we're comparing two numbers in floating point representation, so instead of y1 == y2 we must set a tolerance. I've chosen it as eps, but it's up to you to decide.
To draw a circle around this point, you can compute its points and then plot them, but a better approach would be to plot one point with a blown-up circle marker (credit to Jonas for this suggestion):
plot(px, py, 'ro', 'MarkerSize', 18)
This way the dimensions of the circle are not affected by the axes and the aspect ratio of the plot.
Example
x = 0:0.01:30;
y1 = x .^ 2 + 2;
y2 = x .^ 3;
%// Find point of intersection
idx = find(y1 - y2 < eps, 1);
px = x(idx);
py = y1(idx);
figure
plot(x, y1, x, y2, px, py, 'ro', 'MarkerSize', 18)
axis([0 10 0 10])
This should produce the following plot:

In your example, when you have x, y1 and y2
What you can do is
idx = find(abs(y1 - y2) == min(abs(y1 - y2)));
xInter = x(idx)
yInter = y1(idx) % or y2(idx)
If you have x1, y1 and x2, y2, where x1 ~= x2
you could first do 1D interpolation using
yy2 = interp1(x2, y2, x1);
then apply
idx = find(abs(y1 - yy2) == min(abs(y1 - yy2)));
xInter = x1(idx)
yInter = y1(idx) % or yy2(idx)

Excellent post by #EitanT, however I would like to complement this with a different (automated) way to find the intersection (Assuming there is one and the graphs behave nicely).
Here is our starting point:
x = 0:0.01:30;
y1 = x .^2 + 2;
y2 = x .^3 ;
First of all we check whether these values are exactly equal, for non-floating point non-discrete situations this should be sufficient:
idx = find(y1==y2)
If they are never recorded to be exactly equal, an intersection occurs if one surpasses the other, hence we look at the difference:
if isempty(idx)
d = y1-y2;
% At the moment of crossing, the sign will change:
s = diff(sign(d));
% Now just find the point where it changes
f = find(s,1);
end
To summarize this in compact form without additional variables, I would recommend using:
idx = find(y1==y2)
if isempty(idx)
idx = find(diff(sign(y1-y2)),1)
end

Especially when knowing the functions, the symbolic math toolbox can be used.
y1 = x .^2 + 2;
y2 = x .^3 ;
syms x real
intersection=simplify(solve(y1==y2))
Use vpa(intersection) to convert it to a number or double(intersection) to convert it to a floating point value.

Last but not least, perhaps the cleanest way to do this is the command polyxpoly:
[xi,yi] = polyxpoly(x,y1,x,y2)
xi = 1.69560153754948
yi = 4.87508921229275
Good luck!

Related

Optim-nonlinear equation in matlab code

I updated the question to clarify it more. Here is a graph:
For the curve in the attached photo, I hope to draw the curve. I have its equation and it is after simplification will be like this one
% Eq-2
(b*Y* cos(v) + c - k*X*sin(v))^2 + ...
sqrt(k*X*(cos(v) + 1.0) + b*Y*sin(v))^2) - d = 0.0
Where:
v = atan((2.0*Y)/X) + c
and b, c, d and k are constants.
from the attached graph,
The curve is identified in two points:
p1 # (x=0)
p2 # (y=0)
I a new on coding so accept my apologize if my question is not clear.
Thanks
So, after your edit, it is a bit more clear what you want.
I insist that your equation needs work -- the original equation (before your edit) simplified to what I have below. The curve for that looks like your plot, except the X and Y intercepts are at different locations, and funky stuff happens near X = 0 because you have numerical problems with the tangent (you might want to reformulate the problem).
But, after checking your equation, the following code should be helpful:
function solve_for_F()
% graininess of alpha
N = 100;
% Find solutions for all alphae
X = zeros(1,N);
options = optimset('Display', 'off');
alpha = linspace(0, pi/2, N);
x0 = linspace(6, 0, N);
for ii = 1:numel(alpha)
X(ii) = fzero(#(x)F(x, alpha(ii)), x0(ii), options);
end
% Convert and make an X-Y plot
Y = X .* tan(alpha);
plot(X, Y,...
'linewidth', 2,...
'color', [1 0.65 0]);
end
function fval = F(X, alpha)
Y = X*tan(alpha);
% Please, SIMPLIFY in the future
A = 1247745517111813/562949953421312;
B = 4243112111277797/4503599627370496;
V = atan2(2*Y,X) + A;
eq2 = sqrt( (5/33*( Y*sin(V) + X/2*(cos(V) + 1) ))^2 + ...
(5/33*( Y*cos(V) - X/2* sin(V) ))^2 ) - B;
fval = eq2;
end
Results:
So, I was having fun with this (thanks for that)!
Different question, different answer.
The solution below first searches for the constants causing the X and Y intercepts you were looking for (p1 and p2). For those constants that best fit the problem, it makes a plot, taking into account numerical issues.
In fact, you don't need eq. 1, because that's true always for any curve -- it's just there to confuse you, and problematic to use.
So, here it is:
function C = solve_for_F()
% Points of interest
px = 6;
py = 4.2;
% Wrapper function; search for those constants
% causing the correct X,Y intercepts (at px, py)
G = #(C) abs(F( 0, px, C)) + ... % X intercept at px
abs(F(py, 0, C)); % Y intercept at py
% Initial estimate, based on your original equation
C0 = [5/33
1247745517111813/562949953421312
4243112111277797/4503599627370496
5/66];
% Minimize the error in G by optimizing those constants
C = fminsearch(G, C0);
% Plot the solutions
plot_XY(px, py, C);
end
function plot_XY(xmax,ymax, C)
% graininess of X
N = 100;
% Find solutions for all alphae
Y = zeros(1,N);
X = linspace(0, xmax, N);
y0 = linspace(ymax, 0, N);
options = optimset('Display', 'off',...,...
'TolX' , 1e-10);
% Solve the nonlinear equation for each X
for ii = 1:numel(X)
% Wrapper function for fzero()
fcn1 = #(y)F(y, X(ii), C);
% fzero() is probably the fastest and most intuitive
% solver for this problem
[Y(ii),~,flag] = fzero(fcn1, y0(ii), options);
% However, it uses an algorithm that easily diverges
% when the function slope is large. For those cases,
% solve with fminsearch()
if flag ~= 1
% In this case, the minimum of the absolute value
% is searched for (which should be zero)
fcn2 = #(y) abs(fcn1(y));
Y(ii) = fminsearch(fcn2, y0(ii), options);
end
end
% Now plot the X,Y solutions
plot(X, Y,...
'linewidth', 2,...
'color', [1 0.65 0]);
xlabel('X'), ylabel('Y')
axis([0 xmax+.1 0 ymax+.1])
end
function fval = F(Y, X, C)
% Unpack constants
b = C(1); d = C(3);
c = C(2); k = C(4);
% pre-work
V = atan2(2*Y, X) + c;
% Eq. 2
fval = sqrt( (b*Y*sin(V) + k*X*(cos(V) + 1))^2 + ...
(b*Y*cos(V) - k*X* sin(V) )^2 ) - d;
end

2d pchip in Matlab

I know values of z on a (x,y) meshgrid, defined by xgrid, ygrid.
xgrid, and ygrid are not uniform grids.
I need to interpolate value of z off the grid points.
I need interpolants similar to 'pchip', because the problem at hand requires shape-preseving, and 'pchip' has better shape-preserving properties than e.g. 'spline'.
My current code:
xgrid = [0.01 0.1 0.5 1]';
ygrid = [0.01 0.1 0.5 1];
z = 0.01./(repmat(xgrid,[1 4]).*repmat(ygrid,[4 1]));
x1 = 0.05;
y1 = 0.05;
[xmesh,ymesh] = ndgrid(xgrid,ygrid);
interpolant1 = griddedInterpolant(xmesh,ymesh,z,'cubic');
z1 = interpolant1(x1, y1);
for ix = 1:length(xgrid);
interpolant2(ix) = interp1(ygrid, z(ix,:), y1, 'pchip');
end
z1 = interp1(xgrid, interpolant2, x1, 'pchip');
In my example, interpolant1 will use 'spline' instead of 'cubic' and seems less accurate due to overshooting (http://blogs.mathworks.com/cleve/2012/07/16/splines-and-pchips/). However, interpolant1 is much faster.
My main question: what can I do to make my code for interpolant2 more efficient? vectorization? use an alternative to interp1?

ContourPlot and inequalitie plot together

Im new to matlab and I want to plot a ContourPlot together with two inequalities but I dont know how. The function that I want to plot its ContourPlot is something like this:
Z = (X-2).^2 + (Y-1).^2;
and here are the two inequalities:
ineq1 = X.^2 - Y <= 2;
ineq2 = X + Y <= 2;
this is what I have dodne so far:
[X,Y] = meshgrid(-4:.2:4,-4:.2:4);
Z = (X-2).^2 + (Y-1).^2;
[C,h] = contour(X,Y,Z);
clabel(C,h)
ineq1 = X.^2 - Y <= 2;
ineq2 = X + Y <= 2;
range = (-4:.2:4);
hold on
plot(range,ineq1, range, ineq2)
hold off
but this does not feel right.
What I want to do is to visualize an optimization problem. First I want to plot the ContourPlot of the function and then the possible areas in that same plot, It would be great if I could show the intersection areas too.
If you want to draw the boundaries of the inequalities onto the contour plot, you can do this with line.
[X,Y] = meshgrid(-4:.2:4,-4:.2:4);
Z = (X-2).^2 + (Y-1).^2;
[C,h] = contour(X,Y,Z);
clabel(C,h)
x_vect = (-4:.05:4);
y_ineq1 = x_vect.^2 - 2;
y_ineq2 = 2 - x_vect;
line(x_vect, y_ineq1);
line(x_vect, y_ineq2);
Coloring the intersection area is a bit more tricky, and I'm not sure if it's exactly what you want to do, but you could look into using patch, something like
% Indexes of x_vect, y_ineq1 and y_ineq2 for region where both satisfied:
region_indexes = find(y_ineq1<y_ineq2);
region_indexes_rev = region_indexes(end:-1:1);
% To plot this area need to enclose it
% (forward along y_ineq1 then back along y_ineq2)
patch([x_vect(region_indexes),x_vect(region_indexes_rev)],...
[y_ineq1(region_indexes),y_ineq2(region_indexes_rev)],...
[1 0.8 1]) % <- Color as [r g b]
% May or may not need following line depending on MATLAB version to set the yaxes
ylim([-4 4])
% Get the original plot over the top
hold on
[C,h] = contour(X,Y,Z);
clabel(C,h)
hold off

fill function in MATLAB

I'm having issues unterstanding the function fill in MATLAB , I have a PSD of a file the I want to change it background like :
[xPSD,f] = pwelch(x,hanning(4096),2048,4096*2 ,fs);
plot(f,10*log10(xPSD));
x= f(100:150);
y= 10*log10(xPSD(100:150))
fill(x,y,'y')
the result is in the right direction but not what I need :
I would like get the color tell x axis like :
is their a way to do this
A working solution is:
[xPSD,f] = pwelch(x,hanning(4096),2048,4096*2 ,fs);
plot(f,10*log10(xPSD));
hold on
x= f(100:150);
y= 10*log10(xPSD(100:150));
yMax = ylim;
yMax = yMax(2);
x = x'; % Use this line only in the case that the size(x, 1) > 1
X = [x fliplr(x)];
Y = [y' ones(1, length(y)) .* yMax];
fill(X, Y, 'y')
What you were missing is that fill method looks for an area to fill. In the above code the area is defined by pairs of points. That, for the first (i.e. lower part) of the area we have the x vector and the y points. The second area (i.e. the upper part) is defined by the reversed vector x (image your pencil to first starting drawing towards rights for the lower part and then for the upper going left) and the points of the upper limit of your axes.
Edit:
Minimal example with the handel data from MATLAB:
load handel;
x = y; % Just to be consistent with the OP
fs = Fs; % Just to be consistent with the OP
[xPSD,f] = pwelch(x,hanning(4096),2048,4096*2 ,fs);
plot(f,10*log10(xPSD));
hold on
x= f(100:150);
y= 10*log10(xPSD(100:150));
yMax = ylim;
yMax = yMax(2);
x = x'; % Use this line only in the case that the size(x, 1) > 1
X = [x fliplr(x)];
Y = [y' ones(1, length(y)) .* yMax];
fill(X, Y, 'y')
xlim([0 200]) % To focus on the result
The result is:
Yes, there is always a way ;)
In your case, you simply need to add two points in x and y that go to the top boudary of the plot:
x = f(100:150);
y = 10*log10(xPSD(100:150))
% Add two points
Y = ylim;
x = [x(1) ; x(:) ; x(end)];
y = [Y(2) ; y(:) ; Y(2)];
% Display filled area
fill(x,y,'y')
Best,

Using contour to plot function

I try to use contour to plot this function
3y + y^3 - x^3 = 5
I try contour(3*y+y^3-x^3-5) but it doesn't work.
How can I use contour to plot this function?
Are x and y properly defined as 2x2 matrices? If so then the "power" operator needs to be done on a component-wise basis (.^3 instead of ^3).
This works:
[x,y] = meshgrid(-2:.2:2,-2:.2:2);
contour(3*y+y.^3-x.^3-5)
Maybe you can try fcontour, which plots the contour lines of the function z = f(x,y) for constant levels of z over the default interval [-5 5] for x and y.
f = #(x,y) 3*y + y.^3 - x.^3 - 5;
fcontour(f)
Output:
I'm not convinced this addresses all parts of your question but it's a start. If you absolutely want contour to call a function, you can adjust my example to contour(X,Y,fh(X,Y)).
Better Approach
fh=#(x,y) 3*y + y.^3 - x.^3 -5; % <--- This is your function
x = (-4:.25:4)';
y = (-2:.25:2)';
[X,Y] = meshgrid(x,y);
Z = fh(X,Y);
contour(X,Y,fh(X,Y))
The Direct Approach (not preferred but works)
Notice the Z is transposed to make this work.
fh=#(x,y) 3*y + y.^3 - x.^3 -5; % <----this is your function
X = (-4:.25:4)';
Y = (-2:.25:2)';
Z = zeros(length(X),length(Y));
for i = 1:length(X)
for j = 1:length(Y)
xi = X(i);
yj = Y(j);
Z(i,j) = fh(xi,yj);
end
end
contour(X,Y,Z','LevelList',-60:10:60,'ShowText','on','LineWidth',1.4) % Fancied it up a bit