How do I plot relations in matlab? - matlab

I want to plot relations like y^2=x^2(x+3) in MATLAB without using ezplot or doing algebra to find each branch of the function.
Does anyone know how I can do this? I usually create a linspace and then create a function over the linspace. For example
x=linspace(-pi,pi,1001);
f=sin(x);
plot(x,f)
Can I do something similar for the relation I have provided?

What you could do is use solve and allow MATLAB's symbolic solver to symbolically solve for an expression of y in terms of x. Once you do this, you can use subs to substitute values of x into the expression found from solve and plot all of these together. Bear in mind that you will need to cast the result of subs with double because you want the numerical result of the substitution. Not doing this will still leave the answer in MATLAB's symbolic format, and it is incompatible for use when you want to plot the final points on your graph.
Also, what you'll need to do is that given equations like what you have posted above, you may have to loop over each solution, substitute your values of x into each, then add them to the plot.
Something like the following. Here, you also have control over the domain as you have desired:
syms x y;
eqn = solve('y^2 == x^2*(x+3)', 'y'); %// Solve for y, as an expression of x
xval = linspace(-1, 1, 1000);
%// Spawn a blank figure and remember stuff as we throw it in
figure;
hold on;
%// For as many solutions as we have...
for idx = 1 : numel(eqn)
%// Substitute our values of x into each solution
yval = double(subs(eqn(idx), xval));
%// Plot the points
plot(xval, yval);
end
%// Add a grid
grid;
Take special care of how I used solve. I specified y because I want to solve for y, which will give me an expression in terms of x. x is our independent variable, and so this is important. I then specify a grid of x points from -1 to 1 - exactly 1000 points actually. I spawn a blank figure, then for as many solutions to the equation that we have, we determine the output y values for each solution we have given the x values that I made earlier. I then plot these on a graph of these points. Note that I used hold on to add more points with each invocation to plot. If I didn't do this, the figure would refresh itself and only remember the most recent call to plot. You want to put all of the points on here generated from all of the solution. For some neatness, I threw a grid in.
This is what I get:

Ok I was about to write my answer and I just saw that #rayryeng proposed a similar idea (Good job Ray!) but here it goes. The idea is also to use solve to get an expression for y, then convert the symbolic function to an anonymous function and then plot it. The code is general for any number of solutions you get from solve:
clear
clc
close all
syms x y
FunXY = y^2 == x^2*(x+3);
%//Use solve to solve for y.
Y = solve(FunXY,y);
%// Create anonymous functions, stored in a cell array.
NumSol = numel(Y); %// Number of solutions.
G = cell(1,NumSol);
for k = 1:NumSol
G{k} = matlabFunction(Y(k))
end
%// Plot the functions...
figure
hold on
for PlotCounter = 1:NumSol
fplot(G{PlotCounter},[-pi,pi])
end
hold off
The result is the following:

n = 1000;
[x y] = meshgrid(linspace(-3,3,n),linspace(-3,3,n));
z = nan(n,n);
z = (y .^ 2 <= x .^2 .* (x + 3) + .1);
z = z & (y .^ 2 >= x .^2 .* (x + 3) - .1);
contour(x,y,z)
It's probably not what you want, but I it's pretty cool!

Related

How to plot my differential equation with quiver?

I want to solve my differential equation and plot velocity vectors but I am having some trouble with that. I tried this:
syms y(x);
ode = (1+exp(x))*y*diff(y,x)-2*exp(x) == 0;
ySol = dsolve(ode)
[X,Y] = meshgrid(-2:.2:2);
Z = 2*exp(X)/((1+exp(X)).*Y);
[DX,DY] = gradient(Z,.2,.2);
figure
contour(X,Y,Z)
hold on
quiver(X,Y,DX,DY)
hold off
and I get this error:
Warning: Matrix is singular to working precision.
Warning: Contour not rendered for non-finite ZData
It is probably something simple that I do not see but I am just starting using Matlab and I cold not find a right way to do my task. Please help me...
EDIT
As bconrad suggested, I changed my Z function like this:
Z = 2*exp(X)/((1+exp(X)).*Y);
and the previous errors are fixed. However, my prime goal, to plot velocity vectors is not accomplished yet because I get a graph like this:
Don’t have the ability to check at the moment, but I reckon you want an element by element division in that line. You’re missing a dot on the division, try
Z = 2*exp(X)./((1+exp(X)).*Y);
I took a closer look once at my station. The zero-division mentioned by Pablo forces inf's in Z, so quiver get's confused when scaling the vectors (understandably) and just doesn't show them. Try this (with the ode part removed):
[X,Y] = meshgrid(-2 : .2 : 2);
Z = 2 * exp(X) ./ ((1 + exp(X)) .* Y);
Z(isinf(Z)) = nan; % To avoid 0-division problems
[DX, DY] = gradient(Z, .2, .2);
figure
contour(X, Y, Z, 30, 'k')
hold on
quiver(X, Y, DX, DY, 6)
hold off
I've done 3 things here:
Added the line Z(isinf(Z)) = nan; forcing infinite values to be essentially ignored by quiver
Added the arguments 30, 'k' to the contour function to show 30 lines, and make them black (a bit more visible)
Added the argument 6 to the quiver function. This overrides the automatic length-scaling of the vectors.
You'll want to play with the arguments in the contour and quiver functions to make your figure appear as you'd like.
PS: There is a handy arrow function on the file exchange that I find gives better control when creating vector field plots. See https://www.mathworks.com/matlabcentral/fileexchange/278-arrow - the ratings do it justice.

Finding values of x for a given y when approaching a limit

I'm trying to find two x values for each y value on a plot that is very similar to a Gaussian fn. The difficulty is that I need to be able to find the values of x for several values of y even when the gaussian fn is very close to zero.
I can't post an image due to being a new user, however think of a gaussian function and then the regions where it is close to zero on either side of the peak. This part where the fn is very close to reaching zero is where I need to find the x values for a given y.
What I've tried:
When the fn is discrete: I have tried interp1, however I get the error that it is not strictly monotonic increasing because of the many values that are close to zero.
When I fit a two-term gaussian:
I use fzero (fzero(function-yvalue)) however I get a lot of NaN's. These might be from me not having a close enough 'guess' value??
Does anyone have any other suggestions for me to try? Or how to improve what I've already attempted?
Thanks everyone
EDIT:
I've added a picture below. The data that I actually have is the blue line, while the fitted eqn is in red. The eqn should be accurate enough.
Again, I'm trying to pick out x values for a given y where y is very small (approaching 0).
I've tried splitting the function into left and right halves for the interpolation and fzero method.
Thanks for your responses anyway, I'll have a look at bisection.
Fitting a Gaussian seems to be uneffective, as its deviation (in the x-coordinate) from the real data is noticeable.
Since your data is already presented as a numeric vector y, the straightforward find(y<y0) seems adequate. Here is a sample code, in which the y-values are produced from a perturbed Gaussian.
x = 0:1:700;
y = 2000*exp(-((x-200)/50).^2 - sin(x/100).^2); % imitated data
plot(x,y)
y0 = 1e-2; % the y-value to look for
i = min(find(y>y0)); % first entry above y0
if i == 1
x1 = x(i);
else
x1 = x(i) - y(i)*(x(i)-x(i-1))/(y(i)-y(i-1)); % linear interpolation
end
i = max(find(y>y0)); % last entry above y0
if i == numel(y)
x2 = x(i);
else
x2 = x(i) - y(i)*(x(i)-x(i+1))/(y(i)-y(i+1)); % linear interpolation
end
fprintf('Roots: %g, %g \n', x1, x2)
Output: Roots: 18.0659, 379.306
The curve looks much like your plot.

Matlab reversed 2d interpolation interp2

I have a function V that is computed from two inputs (X,Y). Since the computation is quite demanding I just perform it on a grid of points and would like to rely on 2d linear interpolation. I now want to inverse that function for fixed Y. So basically my starting point is:
X = [1,2,3];
Y = [1,2,3];
V =[3,4,5;6,7,8;9,10,11];
Is is of course easy to obtain V at any combination of (X,Y), for instance:
Vq = interp2(X,Y,V,1.8,2.5)
gives
Vq =
8.3000
But how would I find X for given V and Y using 2d linear interploation? I will have to perform this task a lot of times, so I would need a quick and easy to implement solution.
Thank you for your help, your effort is highly appreciated.
P.
EDIT using additional info
If not both x and y have to be found, but one of them is given, this problem reduces to finding a minimum in only 1 direction (i.e. in x-direction). A simple approach is formulating this in a problem which can be minizmied by an optimization routine such as fminsearch. Therefore we define the function f which returns the difference between the value Vq and the result of the interpolation. We try to find the x which minimizes this difference, after we give an intial guess x0. Depending on this initial guess the result will be what we are looking for:
% Which x value to choose if yq and Vq are fixed?
xq = 1.8; % // <-- this one is to be found
yq = 2.5; % // (given)
Vq = interp2(X,Y,V,xq,yq); % // 8.3 (given)
% this function will be minimized (difference between Vq and the result
% of the interpolation)
f = #(x) abs(Vq-interp2(X, Y, V, x, yq));
x0 = 1; % initial guess)
x_opt = fminsearch(f, x0) % // solution found: 1.8
Nras, thank you very much. I did something else in the meantime:
function [G_inv] = G_inverse (lambda,U,grid_G_inverse,range_x,range_lambda)
for t = 1:size(U,1)
for i = 1:size(U,2)
xf = linspace(range_x(1), range_x(end),10000);
[Xf,Yf] = meshgrid(xf,lambda);
grid_fine = interp2(range_x,range_lambda,grid_G_inverse',Xf,Yf);
idx = find (abs(grid_fine-U(t,i))== min(min(abs(grid_fine-U(t,i))))); % find min distance point and take x index
G_inv(t,i)=xf(idx(1));
end
end
G_inv is supposed to contain x, U is yq in the above example and grid_G_inverse contains Vq. range_x and range_lambda are the corresponding vectors for the grid axis. What do you think about this solution, also compared to yours? I would guess mine is faster but less accurate. Spped is, however, a major issue in my code.

Plotting the result of a 2 parameter function in matlab (3D Graph)

Basically, I have a function f(X,Y) that would return one value for each X,Y that I give. Is there any function in matlab where I can pass the function f, the ranges for X,Y so that it plots a 3d graph showing the magnitude of f (along the z axis) for all values within the given range.
ezplot3, does this kind of, but it takes only one parameter 't'. I am very new to matlab and am trying my best to learn it fast, but I couldnt find much regarding this. Any help would be appreciated
Keep in mind, that with matlab, you're never really plotting "functions"; You're plotting arrays/vectors. So instead of trying to plot g = f(X,Y), you'll actually by plotting the vectors X, Y, and g, where X and Y are your original inputs and g is a vector containing your outputs.
I'm having a hard time visualizing what exactly you're trying to plot but basically, you can follow any standard matlab plotting example such as: http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/plotting.html
It does not produce a 3D plot, but I have found the 2D scatter plot useful for this kind of task before:
scatter(x, y, 5, z)
Where z is the value of the function at the point (x, y) will produce something similar to what you want. Its perhaps not quite as pretty as a full 3D plot but can be used to good effect.
See:
http://www.mathworks.com/matlabcentral/fileexchange/35287-matlab-plot-gallery-scatter-plot-2d/content/html/Scatter_Plot_2D.html
Here is some (very ugly) code I put together to demonstrate the difference:
j=1;
y = -100:1:100;
for i = -100:1:100
y = [y -100:1:100];
count = 0;
while count < 202;
x(j) = i;
j = j+1;
count = count + 1;
end
end
z = (abs(x) + abs(y));
figure(1)
scatter(x, y, 10, z)
h=colorbar;
figure(2)
ezsurf('(abs(x) + abs(y))')
Well, this is what I was going for : http://www.mathworks.com/help/matlab/ref/ezsurf.html
if i do this
ezsurf('f(x,y)');
I get the 3d graph I wanted.
Thanks anyways!

How do you plot elliptic curves over a finite field using matlab

I need to draw an elliptic curve over the finite field F17(in other words, I want to draw some specific dots on the curve), but somehow I don't get it right.
The curve is defined by the equation:
y^2 = x^3 +x + 1 (mod 17)
I tried the way below, but it can't work.
for x = 0:16, plot(x, mod(sqrt(x^3+x+1), 16),'r')', end
Can someone help ?
[Update]
According to Nathan and Bill's suggestions, here is a slightly modified version.
x = 0:18
plot(mod(x,16), mod(sqrt(x.^3+x+1), 16),'ro')
However, I feel the figure is WRONG , e.g.,y is not an integer when x=4 .
You have to test all points that fulfill the equation y^2 = x^3 +x + 1 (mod 17). Since it is a finite field, you cannot simply take the square root on the right side.
This is how I would go about it:
a=0:16 %all points of your finite field
left_side = mod(a.^2,17) %left side of the equation
right_side = mod(a.^3+a+1,17) %right side of the equation
points = [];
%testing if left and right side are the same
%(you could probably do something nicer here)
for i = 1:length(right_side)
I = find(left_side == right_side(i));
for j=1:length(I)
points = [points;a(i),a(I(j))];
end
end
plot(points(:,1),points(:,2),'ro')
set(gca,'XTick',0:1:16)
set(gca,'YTick',0:1:16)
grid on;
Matlab works with vectors natively.
your syntax was close, but needs to be vectorized:
x = 0:16
plot(x, mod(sqrt(x.^3+x+1), 16),'r')
Note the . in x.^3. This tells Matlab to cube each element of x individually, as opposed to raising the vector x to the 3rd power, which doesn't mean anything.
You can use this code if you want to plot on Real numbers:
syms x y;
v=y^2-x^3-x-1;
ezplot(v, [-1,3,-5,5]);
But, for plot in modulo, at first you can write below code;
X=[]; for x=[0:16], z=[x; mod(x^3+x+1,17)]; X=[X, z]; end, X,
Then, you can plot X with a coordinate matrix.