Contour plotting a function in matlab over n levels - matlab

This script f = #(x,y) (1-x)^2 + 100*(y-x^2)^2; fcontour(f,[-2,2]);
draws the contours of the function, over the interval [-2,2]. Is it possible to display the contour lines over the levels 1,2,4,...2048, i.e over some v = 1:2:2048 ? The guide I found specifies how to do this for a matrix. Can I do this without replacing my function with some Z array ( The values of f on the interval )?

Related

MATLAB: polyval function graphs multiple lines for N>1

I am trying to graph a polynomial function using the following code:
y = polyfit(P,C,3);
Line = polyval(y, P);
y =
2.0372e-14 -4.0614e-09 0.0002 2.6060
figure
plot(P,C,'.')
hold on
plot(P, Line, '-')
legend('Observations','y')
axis([0 90000 0 10])
The problem is, it produces multiple lines like this:
This problem does not occur if I set N = 1 or y = polyfit(P,C,1);. In that case I get a proper graph with one line:
How can I graph just 1 line for N = 3?
Here is an Excel version of what I am trying to produce in Matlab:
This is because your observations P are in an arbitrary order: Matlab is going from point to point in that order. You don't actually need to plot the fitted curve at each value P, you just need to plot the fitted curve over the range of P:
Pfitted = linspace(min(P),max(P),1000) % Generate 1000 equally spaced points
Cfitted = polyval(y,Pfitted) % Fit to these points
plot(Pfitted,Cfitted,'-')

How can I use the Second Derivative test to find Maxima and Minima in MATLAB

I'm looking to create a function that takes an equation and marks the maxima and/or minima, and asymptotes on a graph.
From Calc 1, I remember using the Second Derivative Test.
I started by solving for the roots of the first derivative - but am not sure how I can plot where the point in this vector intersect my original equation.
syms x; %//
f = sin(x) %// Define equation as a function
df=diff(f) %// First derivatives
ddf=diff(df) %// Second Derivatives
I found the roots for the x-values of these points with dfRoots = solve(df)
and then created a vector of them called dfRoots_realDouble
dfRoots_double = double(dfRoots);
dfRoots_realDouble = real(dfRoots_double);
dfRoots_realDouble represent the x-values i need, but I dont know how to plot them as points and separate minima from maxima, etc
I'd like to be able to put in any function, like sin(6*(x^5) + 7*(x^3)+8*(x^2)) on [-1,1] and it highlight all the maxima with one marker, and all the minima with another.
If you sort the roots, you will have an alternating vector of maximums and minimums. Use the second derivative to determine if your vector of roots starts with a maximum or a minimum and then split the vector.
roots = sort([-3 4 2 -5]);
is_max = (subs(ddf, x, roots(1)) < 0)
if is_max
max_points = roots(1:2:end)
min_points = roots(2:2:end)
else
max_points = roots(2:2:end)
min_points = roots(1:2:end)
end
% plot with two different symbols
plot(max_points, subs(f, x, max_points), 'or',...
min_points, subs(f, x, min_points), '*k')

Matlab - How can I get the expression of the level curves of a function?

I would like to obtain the level curves of a given function z=f(x,y) without using the countours function in the Matlab environment.
By letting Z equal to some constant 'c' we get a single level curve. I would like to obtain an expression of the resulting function of the form y=f(x) to be able to study other properties of it.
Basic: Example 1: Easy game
Let's consider the problem of plotting level curves of z=-x^2-y^2+100 for x,y:-10;10 and z=1.
[X,Y] = meshgrid(-10:.1:10);
Z = -X.^2+-(Y).^2+100;
surf(X,Y,Z)
we obtain the following figure:
The countour function gives me what I was looking for:
h=[1,1]
contour(X,Y,Z,h)
I can get the same result by solving the equation with respect to x
syms x y;
soly = solve(1==-x.^2-y^2+100, y)
t=soly(1)
x=-10:0.1:10;
figure;
plot(x,(99-x.^2).^(1/2));
hold on
plot(x,-(99-x.^2).^(1/2));
soly =
(99 - x^2)^(1/2)
-(99 - x^2)^(1/2)
The Problem: Example 2
Let's consider the following 3D function.
This function is the sum of guassians with random centers, variances and peaks. You can get it with the following code:
%% Random Radial Basis functions in space
disp('3D case with random path - 10 rbf:');
N = 10 % number of random functions
stepMesh = 0.1;
Z = zeros((XMax-XMin)/stepMesh+1,(XMax-XMin)/stepMesh+1);
[X,Y] = meshgrid(XMin:stepMesh:XMax);
% random variance in [a;b] = [0.3;1.5]
variances = 0.3 + (1.5-0.3).*rand(N,1);
% random amplitude [0.1;1]
amplitudes = 0.1 + (1-0.1).*rand(N,1);
% Random Xcenters in [-XMin;xMax]
Xcenters = XMin+ (XMax-XMin).*rand(N,1);
Ycenters = YMin+ (YMax-YMin).*rand(N,1);
esp=zeros(N,1);
esp=1./(2*(variances).^2);
for i=1:1:N
disp('step:')
disp(i)
Xci=Xcenters(i,1)*ones((XMax-XMin)/stepMesh+1,((XMax-XMin)/stepMesh+1)*2);
Yci=Ycenters(i,1)*ones((YMax-YMin)/stepMesh+1,((YMax-YMin)/stepMesh+1)*2);
disp('Radial Basis Function: [amplitude,variance,center]');
disp(amplitudes(i,1))
disp(variances(i,1))
disp(Xcenters(i,1))
disp(Ycenters(i,1))
Z = Z + 1*exp(-((X-Xci(:,1:((XMax-XMin)/stepMesh+1))).^2+(Y-Yci(:,((XMax-XMin)/stepMesh+2):((YMax-YMin)/stepMesh+1)*2)).^2)*esp(i,1).^2);
end
surf(X,Y,Z)
The countour3 function draws a contour plot of matrix Z in a 3-D view, which is really nice, but it doesn't give me the expression of these functions in 2D.
figure;
contour3(X,Y,Z);
grid on
box on
view([130,30])
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
The Question:
How can I get an explicit expression of the level curves of the second example?

Curve fitting with 5 parameters in Matlab

I am working on a curve fitting problem with the input function of the form
n=((xi-xa)-a*cos(theta))^2+(h-a*sin(theta))^2;
d=((xi-xa)+a*cos(theta))^2+(h+a*sin(theta))^2;
v=k*log(n/d) : Input function
Here xa,a,theta,h and k are parameters and we are required to compute v(xi)
The plot looks like this
Here blue dots represent observed value and red line is the theoretical curve obtained from the input function.
This fitting process was done by manually varying the parameters and matching the curves using hit and trial.
Could this be accomplished using any optimization technique in Matlab. if so how ?
You can try to use lsqcurvefit (http://nl.mathworks.com/help/optim/ug/lsqcurvefit.html), e.g.
function F = myfun(x,xdata)
%your parameters xa,a,theta,h,k
%map to parameter vector x(1),x(2),x(3),x(4),x(5)
n = ((xdata-x(1))-x(2)*cos(x(3)))^2+(x(4)-x(2)*sin(x(3)))^2;
d = ((xdata-x(1))+acos(x(3)))^2+(x(4)+asin(x(3)))^2;
F = x(5)*log(n/d);
end
and a call to solver
x0 = [1;1;1;1;1]; % your guess for starting values of the x vector of parameters
x = lsqcurvefit(#myfun,x0,xdata,ydata);

How can I contour plot a custom function?

I have a custom function which returns either 0 or 1 depending on two given inputs:
function val = myFunction(val1, val2)
% logic to determine if val=1 or val=0
end
How can I create a contour plot of the function over the x,y coordinates generated by the following meshgrid?
meshgrid(0:.5:3, 0:.5:3);
This plot will just simply display where the function is 0 or 1 on the contour map.
If your function myFunction is not designed to handle matrix inputs, then you can use the function ARRAYFUN to apply it to all the corresponding entries of x and y:
[x,y] = meshgrid(0:0.5:3); %# Create a mesh of x and y points
z = arrayfun(#myFunction,x,y); %# Compute z (same size as x and y)
Then you could use the function CONTOUR to generate a contour plot for the above data. Since your z data only has 2 different values, it would probably make sense for you to only plot one contour level (which would be at a value of 0.5, halfway between your two values). You might also want to instead use the function CONTOURF, which produces color-filled contours that will clearly show where the ones and zeroes are:
contourf(x,y,z,1); %# Plots 1 contour level, filling the area on either
%# side with different color
NOTE: Since you are plotting data that only has ones and zeroes, plotting contours may not be the best way to visualize it. I would instead use something like the function IMAGESC, like so:
imagesc(x(1,:),y(:,1),z);
Keep in mind the y-axis in this plot will be reversed relative to the plot generated by CONTOURF.
The following will do it:
function bincontour
clear; clc;
xrange = 0:.5:3;
yrange = 1:.5:5;
[xmesh, ymesh] = meshgrid(xrange, yrange);
z = arrayfun(#myFunction, xmesh, ymesh);
contourf(xrange, yrange, z, 5)
end
function val = myFunction(val1, val2)
val = rand() > 0.5;
end