drawing a contour for n* 1 matrix - matlab

I am new to matlab and simulink.
I have a function P which take two inputs distance and velocity (each one as a function)..
I modeled my system in simulink and I wrote the P function in the block called Matlab function since the function has if statement for example ( if v < 0 then P = 1 else P = 1 / v+d ).
The velocity and the distance function are in form of sine and cosine with different frequencies..
Now I added the block to workspace for P, velocity and distance as an array. In the workspace I have array of n*1 for all of the three.
I want to draw a contour for the P according to the velocity and the distance but the contour accept at least a matrix 2*2 ..
How can I change the P to be a matrix without affecting my work and I want to draw the contour for P with respect to the velocity and the distance ??

Here is what you can do:
See which speeds and velocities you have, and define a 2 dimensional grid based on that.
Try to give each point on the grid the correct value (based on your simulation output)
Use the contour function.
Note that drawing a contour mostly makes sense if you have a significant part of the grid covered. Otherwise try help plot3 as #thewaywewalk suggested.

Related

Solving integral in Matlab containing unknown variables?

The task is to create a cone hat in Matlab by creating a developable surface with numerical methods. There are 3 parts of which I have done 2. My question is regarding part 3 where I need to calculate the least rectangular paper surface that can contain the hat. And I need to calculate the material waste of the paper.
YOU CAN MAYBE SKIP THE LONG BACKGROUND AND GO TO LAST PARAGRAPH
BACKGROUND:
The cone hat can be created with a skewed cone with its tip located at (a; 0; b) and with a circle-formed base.
x = Rcos u,
y = Rsin u
z = 0
0<_ u >_2pi
with
known values for R, a and b
epsilon and eta ('n') is the curves x- and y- values when the parameter u goes from 0 to 2pi and alpha is the angle of inclination for the curve at point (epsilon, eta). Starting values at A:
u=0, alhpa=0, epsilon=0, eta=0.
Curve stops at B where the parameter u has reached 2pi.
1.
I plotted the curve by using Runge-Kutta-4 and showed that the tip is located at P = (0, sqrt(b^2 + (R-alpha)^2))
2.
I showed that by using smaller intervals in RK4 I still get quite good accuracy but the problem then is that the curve isn't smooth. Therefore I used Hermite-Interpolation of epsilon and eta as functions of u in every interval to get a better curve.
3.
Ok so now I need to calculate the least rectangular paper surface that can contain the hat and the size of the material waste of the paper. If the end angle alpha(2pi) in the template is pi or pi/2 the material waste will be less. I now get values for R & alpha (R=7.8 and alpha=5.5) and my task is to calculate which height, b the cone hat is going to get with the construction-criteria alpha(2pi)=pi (and then for alpha(2pi)=pi/2 for another sized hat).
So I took the first equation above (the expression containing b) and rewrote it like an integral:
TO THE QUESTION
What I understand is that I need to solve this integral in matlab and then choose b so that alpha(2pi)-pi=0 (using the given criteria above).
The values for R and alpha is given and t is defined as an interval earlier (in part 1 where I did the RK4). So when the integral is solved I get f(b) = 0 which I should be able to solve with for example the secant method? But I'm not able to solve the integral with the matlab function 'integral'.. cause I don't have the value of b of course, that is what I am looking for. So how am I going to go about this? Is there a function in matlab which can be used?
You can use the differential equation for alpha and test different values for b until the condition alpha(2pi)=pi is met. For example:
b0=1 %initial seed
b=fsolve(#find_b,b0) %use the function fsolve or any of your choice
The function to be solved is:
function[obj]=find_b(b)
alpha0=0 %initual valur for alpha at u=0
uspan=[0 2*pi] %range for u
%Use the internal ode solver or any of your choice
[u,alpha] = ode45(#(u,alpha) integrate_alpha(u,alpha,b), uspan, alpha0);
alpha_final=alpha(end) %Get the last value for alpha (at u=2*pi)
obj=alpha_final-pi %Function to be solved
end
And the integration can be done like this:
function[dalpha]=integrate_alpha(u,alpha,b)
a=1; %you can use the right value here
R=1; %you can use the right value here
dalpha=(R-a*cos(u))/sqrt(b^2+(R-a*cos(u))^2);
end

Using diff or gradient for symbolic computations?

I am using virtual potential fields to control the movement of a group of robots in a 2D environment, their position is given by a matrix of x and y coordinates. The virtual potential fields depend on a number of variables, one of them is the inter-robot distance. A short (heavily simplified) example of my code is given below.
x = sym('x',[4 2]); % four robots with x and y coordinates
xd = sym('xd',[1 2]); % a single destination
F = sym(ones(4,1)); % one potential function for each robot
for i=1:size(x,1)
for j=1:size(x,1)
if i~=j
F(i) = F(i)/norm(x(i,:)-x(j,:))^2; % infinite potential when any two robots collide
end
end
F(i) = F(i) * norm(x(i,:)-xd)^2; % add an attraction force to the goal
end
So now that I have created symbolic expressions for the potential fields, I need to find their derivative so I can apply steepest descent. Now I'm wondering: does it make any difference whether I use the function gradient or diff to obtain the derivative with respect to the position? To clarify: for robot i I want to take the derivative with respect to xi_1 and xi_2.
Your question, as stated, is bordering on mathematics rather than programming. The gradient is just the generalization of the derivative to multiple dimensions. Yes, for movement in a 2-D plane, it would make sense to use sym/gradient. As the documentation states, if you specify just a scalar for the second argument, sym/gradient becomes equivalent to sym/diff. To properly calculate your 2-D gradient, the second argument must be a two-element vector, e.g., [xi_1 xi_2].

Matlab plot function defined on a complex coordinate

I would like to plot some figures like this one:
-axis being real and imag part of some complex valued vector(usually either pure real or imag)
-have some 3D visualization like in the given case
First, define your complex function as a function of (Re(x), Im(x)). In complex analysis, you can decompose any complex function into its real parts and imaginary parts. In other words:
F(x) = Re(x) + i*Im(x)
In the case of a two-dimensional grid, you can obviously extend to defining the function in terms of (x,y). In other words:
F(x,y) = Re(x,y) + i*Im(x,y)
In your case, I'm assuming you'd want the 2D approach. As such, let's use I and J to represent the real parts and imaginary parts separately. Also, let's start off with a simple example, like cos(x) + i*sin(y) which is based on the very popular Euler exponential function. It isn't exact, but I modified it slightly as the plot looks nice.
Here are the steps you would do in MATLAB:
Define your function in terms of I and J
Make a set of points in both domains - something like meshgrid will work
Use a 3D visualization plot - You can plot the individual points, or plot it on a surface (like surf, or mesh).
NB: Because this is a complex valued function, let's plot the magnitude of the output. You were pretty ambiguous with your details, so let's assume we are plotting the magnitude.
Let's do this in code line by line:
% // Step #1
F = #(I,J) cos(I) + i*sin(J);
% // Step #2
[I,J] = meshgrid(-4:0.01:4, -4:0.01:4);
% // Step #3
K = F(I,J);
% // Let's make it look nice!
mesh(I,J,abs(K));
xlabel('Real');
ylabel('Imaginary');
zlabel('Magnitude');
colorbar;
This is the resultant plot that you get:
Let's step through this code slowly. Step #1 is an anonymous function that is defined in terms of I and J. Step #2 defines I and J as matrices where each location in I and J gives you the real and imaginary co-ordinates at their matching spatial locations to be evaluated in the complex function. I have defined both of the domains to be between [-4,4]. The first parameter spans the real axis while the second parameter spans the imaginary axis. Obviously change the limits as you see fit. Make sure the step size is small enough so that the plot is smooth. Step #3 will take each complex value and evaluate what the resultant is. After, you create a 3D mesh plot that will plot the real and imaginary axis in the first two dimensions and the magnitude of the complex number in the third dimension. abs() takes the absolute value in MATLAB. If the contents within the matrix are real, then it simply returns the positive of the number. If the contents within the matrix are complex, then it returns the magnitude / length of the complex value.
I have labeled the axes as well as placed a colorbar on the side to visualize the heights of the surface plot as colours. It also gives you an idea of how high and how long the values are in a more pleasing and visual way.
As a gentle push in your direction, let's take a slice out of this complex function. Let's make the real component equal to 0, while the imaginary components span between [-4,4]. Instead of using mesh or surf, you can use plot3 to plot your points. As such, try something like this:
F = #(I,J) cos(I) + i*sin(J);
J = -4:0.01:4;
I = zeros(1,length(J));
K = F(I,J);
plot3(I, J, abs(K));
xlabel('Real');
ylabel('Imaginary');
zlabel('Magnitude');
grid;
plot3 does not provide a grid by default, which is why the grid command is there. This is what I get:
As expected, if the function is purely imaginary, there should only be a sinusoidal contribution (i*sin(y)).
You can play around with this and add more traces if you need to.
Hope this helps!

How to use matlab contourf to draw two-dimensional decision boundary

I finished an SVM training and got data like X, Y. X is the feature matrix only with 2 dimensions, and Y is the classification labels. Because the data is only in two dimensions, so I would like to draw a decision boundary to show the surface of support vectors.
I use contouf in Matlab to do the trick, but really find it hard to understand how to use the function.
I wrote like:
#1 try:
contourf(X);
#2 try:
contourf([X(:,1) X(:,2) Y]);
#3 try:
Z(:,:,1)=X(Y==1,:);
Z(:,:,2)=X(Y==2,:);
contourf(Z);
all these things do not correctly. And I checked the Matlab help files, most of them make Z as a function, so I really do not know how to form the correct Z matrix.
If you're using the svmtrain and svmclassify commands from Bioinformatics Toolbox, you can just use the additional input argument (...'showplot', true), and it will display a scatter plot with a decision boundary and the support vectors highlighted.
If you're using your own SVM, or a third-party tool such as libSVM, what you probably need to do is to:
Create a grid of points in your 2D input feature space using the meshgrid command
Classify those points using your trained SVM
Plot the grid of points and the classifications using contourf.
For example, in kind-of-MATLAB-but-pseudocode, assuming your input features are called X1 and X2:
numPtsInGrid = 100;
x1Range = linspace(x1lower, x1upper, numPtsInGrid);
x2Range = linspace(x2lower, x2upper, numPtsInGrid);
[X1, X2] = meshgrid(x1Range, x2Range);
Z = classifyWithMySVMSomehow([X1(:), X2(:)]);
contourf(X1(:), X2(:), Z(:))
Hope that helps.
I know it's been a while but I will give it a try in case someone else will come up with that issue.
Assume we have a 2D training set so as to train an SVM model, in other words the feature space is a 2D space. We know that a kernel SVM model leads to a score (or decision) function of the form:
f(x) = sumi=1 to N(aiyik(x,xi)) + b
Where N is the number of support vectors, xi is the i -th support vector, ai is the estimated Lagrange multiplier and yi the associated class label. Values(scores) of decision function in way depict the distance of the observation x frοm the decision boundary.
Now assume that for every point (X,Y) in the 2D feature space we can find the corresponding score of the decision function. We can plot the results in the 3D euclidean space, where X corresponds to values of first feature vector f1, Y to values of second feature f2, and Z to the the return of decision function for every point (X,Y). The intersection of this 3D figure with the Z=0 plane gives us the decision boundary into the two-dimensional feature space. In other words, imagine that the decision boundary is formed by the (X,Y) points that have scores equal to 0. Seems logical right?
Now in MATLAB you can easily do that, by first creating a grid in X,Y space:
d = 0.02;
[x1Grid,x2Grid] = meshgrid(minimum_X:d:maximum_X,minimum_Y:d:maximum_Y);
d is selected according to the desired resolution of the grid.
Then for a trained model SVMModel find the scores of every grid's point:
xGrid = [x1Grid(:),x2Grid(:)];
[~,scores] = predict(SVMModel,xGrid);
Finally plot the decision boundary
figure;
contour(x1Grid,x2Grid,reshape(scores(:,2),size(x1Grid)),[0 0],'k');
Contour gives us a 2D graph where information about the 3rd dimension is depicted as solid lines in the 2D plane. These lines implie iso-response values, in other words (X,Y) points with same Z value. In our occasion contour gives us the decision boundary.
Hope I helped to make all that more clear. You can find very useful information and examples in the following links:
MATLAB's example
Representation of decision function in 3D space

geometric random graph in a circle

I wanted to generate a set of coordinates distributed uniformly at random within a ball of radius R. Is there any way to do this in Matlab without for loops, in a matrix-like form?
Thanks
UPDATE:
I'm sorry for the confusion. I only need to generate n points uniformly at random over a circle of radius R, not a sphere.
the correct answer is here http://mathworld.wolfram.com/DiskPointPicking.html. The distribution is known as "Disk point picking"
I was about to mark this as a duplicate of a previous question on generating uniform distribution of points in a sphere, but I think you deserve the benefit of doubt here, as although there's a matlab script in the question, most of that thread is python.
This little function given in the question (and I'm pasting it directly from there), is what you need.
function X = randsphere(m,n,r)
% This function returns an m by n array, X, in which
% each of the m rows has the n Cartesian coordinates
% of a random point uniformly-distributed over the
% interior of an n-dimensional hypersphere with
% radius r and center at the origin. The function
% 'randn' is initially used to generate m sets of n
% random variables with independent multivariate
% normal distribution, with mean 0 and variance 1.
% Then the incomplete gamma function, 'gammainc',
% is used to map these points radially to fit in the
% hypersphere of finite radius r with a uniform % spatial distribution.
% Roger Stafford - 12/23/05
X = randn(m,n);
s2 = sum(X.^2,2);
X = X.*repmat(r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2),1,n);
To learn why you can't just use uniform random variable for all three co-ordinates as one might think is the correct way, give this article a read.
For the sake of completeness, here is some MATLAB code for a point-culling solution. It generates a set of random points within a unit cube, removes points that are outside a unit sphere, and scales the coordinate points up to fill a sphere of radius R:
XYZ = rand(1000,3)-0.5; %# 1000 random 3-D coordinates
index = (sum(XYZ.^2,2) <= 0.25); %# Find the points inside the unit sphere
XYZ = 2*R.*XYZ(index,:); %# Remove points and scale the coordinates
One key drawback to this point-culling method is that it makes it difficult to generate a specific number of points. For example, if you want to generate 1000 points within your sphere, how many do you have to create in the cube before culling them? If you scale up the number of points generated in the cube by a factor of 6/pi (i.e. the ratio of the volume of a unit cube to a unit sphere), then you can get close to the number of desired points in the sphere. However, since we're dealing with (pseudo)random numbers after all, we can never be absolutely certain we will generate enough points that fall in the sphere.
In short, if you want to generate a specific number of points, I'd try out one of the other solutions suggested. Otherwise, the point-culling solution is nice and simple.
Not sure if I understand your question correctly, but can't you just generate any random number inside a sphere by setting φ, θ and r, assigned to random numbers?