Helix in Matlab - matlab

I am working to create a helix in Matlab.
Going by the below code:
t = 0:pi/50:20*pi;
(Can you please explain me this syntax or we have to follow this everytime when creating a helix?)
st = sin(t);
ct = cos(t);
plot3(st,ct,t)
As maximum efficiency in a helix angle is between 40 and 45 degrees, if I want to enter the angle as 42, how is it possible in the code?
It would be very helpful if anyone can share their opinion on this
TIA

What happens in the code is merely an execution of the parametric mathematical description of a helix, which you can read up on wikipedia as
x(t) = cos(t)
y(t) = sin(t)
z(t) = t
The first line of your code generates a vector for values of t from 0 to 20pi in steps of pi/50 (i.e., 1000 steps). Since every 2pi means one full rotation (cos and sin are 2pi-periodic), it coincides to 10 turns of the helix (if you want to change this, let t run up to 2*pi*NumberOfRotations). The other two lines generate corresponding vectors for x and y. plot3 plots a line in 3-D where x and y are passed and as argument for z we pass t since z=t.
To change the slope of the helix, use the more general description given by
x(t) = a*cos(t)
y(t) = a*sin(t)
z(t) = b*t
where a is the radius and b/a is the slope. To get 42° use b = a*atand(42). To make sure the aspect ratio is correct in display, use axis equal; after the plot and maybe axis vis3d; if you want to turn it around.

Related

Matlab partial area under the curve

I want to plot the area above and below a particular value in x axis.
The problem i am facing is with discrete values. The code below for instance has an explicit X=10 so i have written it in such a way that i can find the index and calculate the values above and below that particular value but if i want to find the area under the curve above and below 4 this program will now work.
Though in the plot matlab does a spline fitting(or some sort of fitting for connecting discrete values) there is a value for y corresponding to x=4 that matlab computes i cant seem to store or access it.
%Example for Area under the curve and partial area under the curve using Trapezoidal rule of integration
clc;
close all;
clear all;
x=[0,5,10,15,20];% domain
y=[0,25,50,25,0];% Values
LP=log2(y);
plot(x,y);
full = trapz(x,y);% plot of the total area
I=find(x==10);% in our case will be the distance value up to which we want
half = trapz(x(1:I),y(1:I));%Plot of the partial area
How can we find the area under the curve for a value of ie x = 2 or 3 or 4 or 6 or 7 or ...
This is an elaboration of patrik's comment, "first interpolate and then integrate".
For the purpose of this answer I'll assume that the area in question is the area that can be seen in the plot, and since plot connects points by straight lines I assume that linear interpolation is adequate. Moreover, since the trapezoidal rule itself is based on linear interpolation, we only need interpolated values at the beginning and end of the interval.
Starting from the given points
x = [0, 5, 10, 15, 20];
y = [0, 25, 50, 25, 0];
and the integration interval limits, say
xa = 4;
xb = 20;
we first select the data points within the limits
ind = (x > xa) & (x < xb);
xw = x(ind);
yw = y(ind);
and then complete them by interpolation values at the edges:
ya = interp1(x, y, xa);
yb = interp1(x, y, xb);
xw = [xa, xw, xb];
yw = [ya, yw, yb];
Now we can simply apply trapezoidal integration:
area = trapz(xw, yw);
I think that you either need more samples, or to interpolate the data. Another alternative is to use a function handle. Then you need to know the function though. Example using linear interpolation follows.
x0 = [0;5;10;15;20];
y0 = [0,25,50,25,0];
x1 = 0:20;
y1 = interp1(x0,y0,x1,'linear');
xMax = 4;
partInt = trapz(x1(x1<=xMax),y1(x1<=xMax));
Some other kind of interpolation may be suitable, but that is hard to say without more information. Also, this interpolates from the beginning to x. However, I guess figuring out how to change the limits should be easy from here. This solution is different than the former, since it is less depending on the pyramid shape of the data. So to say, it is more general.

Sketch f(x,y)=(21/4)x^2y over the region x^2 <= y <= 1

Can someone share a technique using MATLAB to plot the surface f(x,y)=(21/4)x^2y over the region x^2 <= y <= 1?
Also, if anyone is aware of some tutorials or links that would help with this type of problem, could you please share them?
Thanks.
Here is another approach:
%%
close all
x=linspace(-1,1,40);
g1=x.^2;
g2=ones(1,40);
y=[];
n=20;
for k=0:n
y=[y;g1+(g2-g1)*k/n];
end
x=x(ones(1,n+1),:);
z=21/4*x.^2.*y;
meshz(x,y,z)
axis tight
xlabel('x-axis')
ylabel('y-axis')
view(136,42)
And the result:
And finally, you can map the region (-1,1)x(0,1) in the uv-plane into the region bounded by $y=x^2 and y=1 in the xy-plane with the parametrization:
f(u,v) = (u\sqrt{v},v)
Capture from: https://math.stackexchange.com/questions/823168/transform-rectangular-region-to-region-bounded-by-y-1-and-y-x2
This code produces the same image shown above:
close all
[u,v]=meshgrid(linspace(-1,1,40),linspace(0,1,20));
x=u.*sqrt(v);
y=v;
z=21/4*x.^2.*y;
meshz(x,y,z)
axis tight
xlabel('x-axis')
ylabel('y-axis')
view(136,42)
First off, let's look at your valid region of values. This is telling us that y >= x^2 and also y <= 1. This means that your y values need to be on the positive plane bounded by the parabola x^2 and they also must be less than or equal to 1. In other words, your y values must be bound within the area dictated from y = x^2 to y = 1. Pictorially, your y values are bounded within this shape:
As such, your x values must also be bound between -1 and 1. Therefore, your actual boundaries are: -1 <= x <= 1 and 0 <= y <= 1. However, this only locates our boundaries for x and y but it doesn't handle where the plot has valid values. We'll tackle that later.
Now that we have that established, you can use ezsurf to plot surface plots in MATLAB that are dictated by a 2D equation.
You call ezsurf like so:
ezsurf(FUN, [XMIN,XMAX,YMIN,YMAX]);
FUN is a function or a string that contains the equation you want, and XMIN,XMAX,YMIN,YMAX contain the lowest and highest x and y values you want to plot. Plotting without these values assumes a span from -2*pi to 2*pi in both dimensions. As such, let's create a new function that will handle when we have valid values, and when we don't. Use this code, and save it to a new file called myfun.m. Make sure you save this to your current Working Directory.
function z = myfun(x,y)
z = (21/4)*x.^2.*y;
z(~(x.^2 <= y & y <= 1)) = nan;
end
This will allow you to take a series of x and y values and output values that are dictated by the 2D equation that you have given us. Any values that don't satisfy the condition of x^2 <= y <= 1, you set them to NaN. ezsurf will not plot NaN values.
Now, call ezsurf like so:
ezsurf(#myfun, [-1,1,0,1]);
You thus get:
This will spawn a new figure for you, and there are some tools at the top that will allow you interact with your 3D plot. For instance, you can use the rotation tool that's at the top bar beside the hand to rotate your figure around and see what this looks like. Click on this tool, then left click your mouse and hold the left mouse button anywhere within the surface plot. You can drag around, changing the azimuth and the latitude to get the perspective that you want.
Edit: June 4th, 2014
Noting your comments, we can decrease the jagged edges by increasing the number of points in the plot. As such, you can append a final parameter to ezsurf which is N, the number of points to add in each dimension. Increasing the number of points will decrease the width in between each point and so the plot will look smoother. The default value of N is 60 in both dimensions. Let's try increasing the amount of points in each dimension to 100.
ezsurf(#myfun, [-1,1,0,1], 100);
Your plot will look like:
Hope this helps!
Try the following to make the required function, compute the values, and plot only the region that is desired:
% Make the function. You could put this in a file by itself, if you wanted.
f = #(x,y) (21/4)*x.^2.*y;
[X Y] = meshgrid(linspace(0,1));
Z = f(X,Y);
% compute the values we want to plot:
valsToPlot = (X.^2 <= Y) & (Y <= 1);
% remove the values that we don't want to plot:
X(~valsToPlot) = nan;
Y(~valsToPlot) = nan;
Z(~valsToPlot) = nan;
% And... plot.
figure(59382);
clf;
surf(X,Y,Z);

Documenting matlab code for generating random shapes

Can you please help me document this Matlab code that is supposed to produce random shapes?? The wiggliness of the shapes is supposed to be controlled by the variable degree...
But how the rho (radius values) are produced... I can't really get it....
degree = 5;
numPoints = 1000;
blobWidth = 5;
theta = 0:(2*pi)/(numPoints-1):2*pi;
coeffs = rand(degree,1);
rho = zeros(size(theta));
for i = 1:degree
rho = rho + coeffs(i)*sin(i*theta);
end
phase = rand*2*pi;
[x,y] = pol2cart(theta+phase, rho+blobWidth);
plot(x,y)
axis equal
set(gca,'Visible','off')
theta = 0:(2*pi)/(numPoints-1):2*pi;
So this is just a vector of angles in a revolution, if you plot this theta against a constant rho (after calling pol2cart) you will get a circle:
r = ones(size(theta));
[x,y] = pol2cart(theta, r);
plot(x,y)
axis equal
This should be obvious if you understand what pol2cart does because you have a series of all the angles in a circle and a constant radius for all of them. If you don't understand that (i.e. polar coordinates) then that's a very basic mathematical concept you need to go and read up on your own before trying to understand this code.
OK so now a circle in cartesian coords is just a line in polar coords (i.e. plot(theta, r) noting that the horizontal axis now represents angle and the vertical represents radius). So if we want to randomly mess up our circle, we could randomly mess up our line. Using sin does this in a nice smooth way. Adding random frequencies of many sin waves adds less and less predictable "jitter". I think it would help you to understand if you add the following line to your code:
rho = zeros(size(theta));
hold all
for i = 1:degree
rho = rho + coeffs(i)*sin(i*theta);
plot(theta, rho)
end
and contrast this to (be sure to close your figure window before running this)
rho = zeros(size(theta));
hold all
for i = 1:degree
rho = rho + coeffs(i)*sin(i*theta);
plot(theta, coeffs(i)*sin(i*theta))
end
The second one shows you the different frequencies of sin waves used and the first shows how these sum to create unpredictable wavy lines. Now think of the pol2rect function as bending these lines around to make a "circle". If the line is dead straight you get a perfect circle, if it's wavy you get a "wavy" circle.
degree in your code just controls how many sin waves to add up.
finally phase = rand*2*pi; just randomly rotates your shape after it has been created.
Well, this was an amazing piece of code! But regarding rho. What is done is that you have a circle with base radius of 5 (blobwidth) and then you have a random offset coeffs. Then the offset is added to rho in rho = rho + coeffs(i)*sin(i*theta);. This means that the first loop an offset is added to the circle with frequency 1Hz. This then yields a constant offset. The next loop the frequency increases to 2Hz. Then the offset will be added to every second point and the offset may be negative as well. Then it goes on like this. Finally the coordinate is transformed to polar.
A few comments though. The most readable and the easiest way to create theta is to use linspace. And also, since rho is overwritten in the loop, you may as well define it just as rho = 0;

MATLAB vectors, angles, plots

I apologize for the ambiguous title, but I am not entirely sure how to phrase this one. So bear with me.
I have a matrix of data. Each column and row represents a certain vector (column 1 = row 1, column 2 = row 2, etc.), and every cell value is the cosine similarity between the corresponding vectors. So every value in the matrix is a cosine.
There are a couple of things I want to do with this. First, I want to create a figure that shows all of the vectors on it. I know the cosine of the angle between every vector, and I know the magnitude of each vector, but that is the only information I have - is there some algorithm I can implement that will run through all of the various pair-wise angles and display it graphically? That is, I don't know where all the vectors are in relation to each other, and there are too many data points to do this by hand (e.g. if I only had three vectors, and the angles between them all were 45, 12, and 72 degrees it would be trivial). So how do I go about doing this? I don't even have the slightest idea what sort of mathematical function I would need to do this. (I have 83 vectors, so that's thousands of cosine values). So basically this figure (it could be either 2D or multidimensional, and to be honest I would like to do both) would show all of the vectors and how they relate to each other in space (so I could compare both angles and relative magnitudes).
The other thing I would like to do is simpler but I am having a hard time figuring it out. I can convert the cosine values into Cartesian coordinates and display them in a scatter plot. Is there a way to connect each of the points of a scatter plot to (0,0) on the plot?
Finally, in trying to figure out how to do some of the above on my own I have run into some inconsistencies. I calculated the mean angles and Cartesian coordinates for each of the 83 vectors. The math for this is easy, and I have checked and double-checked it. However, when I try to plot it, different plotting methods give me radically different things. So, if I plot the Cartesian coordinates as a scatter plot I get this:
If I plot the mean angles in a compass plot I get this:
And if I use a quiver plot I get something like this (I transformed this a little by shifting the origin up and to the right just so you can see it better):
Am I doing something wrong, or am I misunderstanding the plotting functions I am using? Because these results all seem pretty inconsistent. The mean angles on the compass plot are all <30 degrees or so, but on the quiver plot some seem to exceed 90 degrees, and on the scatter plot they extend above 30 as well. What's going on here?
(Here is my code:)
cosine = load('LSA.txt');
[rows,columns]=size(cosine);
p = cosine.^2;
pp = bsxfun(#minus, 1, p);
sine = sqrt(pp);
tangent = sine./cosine;
Xx = zeros(rows,1);
Yy = zeros(rows,1);
for i = 1:columns
x = cosine(:,i);
y = sine(:,i);
Xx(i,1) = sum(x) * (1/columns);
Yy(i,1) = sum(y) * (1/columns);
end
scatter(Xx,Yy);
Rr = zeros(rows,1);
Uu = zeros(rows,1);
for j = 1:rows
Rr(j,1) = sqrt(Xx(j,1).^2 + Yy(j,1).^2);
Uu(j,1) = atan2(Xx(j,1),Yy(j,2));
end
%COMPASS PLOT
[theta,rho] = pol2cart(Uu,1);
compass(theta,rho);
%QUIVER PLOT
r = 7;
sx = ones(size(cosine))*2; sy = ones(size(cosine))*2;
pu = r * cosine;
pv = r * sine;
h = quiver(sx,sy,pu,pv);
set(gca, 'XLim', [1 10], 'YLim', [1 10]);
You can exactly solve this problem. The dot product calculates the cosine. This means your matrix is actually M=V'*V
This should be solvable through eigenvalues. And you said you also have the length.
Your only problem - as your original matrix the vectors will be 83 dimensional. Not easy to plot in 2 or 3 dimensions. I think you are over simplifying by just using the average angle. There are some techniques called dimensionality reduction - here's a toolbox. I would suggest a sammon projection on 1-cosine (as this would be the distance of points on the unit ball) to calculate the vectors for such a plot.
In the quiver plot, you are plotting all of the data in the cosine and sine matrices. In the other plots, you are only plotting the means. The first two plots appear to match up, so no problem there.
A few other things. I notice that in
Uu(j,1) = atan2(Xx(j,1),Yy(j,2));
Yy(j,2) is not actually defined, so it seems like this code should fail.
Furthermore, you could define Yy and Xx as:
Xx = mean(cosine,2);
Yy = mean(sine,2);
And also get rid of the other for loop:
Rr = sqrt(Xx.^2 + Yy.^2)
Uu = atan2(Xx,Yy)
I still have to think about your first question, but I hope this was helpful.

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.