Generate 2d plot on Matlab on given range - matlab

Im trying to plot the following on MATLAB not sure how to do it?
Y-axis ranges from -200 to 200
X-axis ranges from 0 to 10
Now the function is
x = linspace (0,10,100);
Yin = 10*sin (2*pi*x);
Ym = Yin*4*cos(2*pi*x);
I'm trying to plot graph for (Yin, Ym) that will show me the range of 0 to 10 on X-axis and -200 to 200 and Y-axis

For the plotting part the answer is:
plot(x,Yin,x,Ym);
axis([min(x),max(x),-200,200]);
But be careful with Ym = Yin*4*cos(2*pi*x); since Yin and x (thus cos(2*pi*x)) are vectors, * is the matrix multiplication. Since both Yin and x have the same shape, it may raise an error. Depending on what you want, you may need the elment-wise multiplication operator .* instead: Ym = 4*Yin.*cos(2*pi*x);

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,'-')

Dom::Interval function in Matlab Error

I am trying to plot f(x)=sin(x) in Matlab, but am having trouble defining my variable x as the interval [0,pi/2]. I have:
x1 = Dom::Interval([0], [1])
y1 = cos(x1)
plot(x1,y1)
However, the interval function in Matlab returns as an unexpected Matlab operator.
Dom::Interval is part of the MuPad interface. Simply create a numeric array from 0 to pi/2 and plot the sin of the result.
x1 = linspace(0, pi/2);
y1 = sin(x);
plot(x1, y1);
linspace generates a numeric array with a default amount of 100 points linearly spaced from 0 to pi/2. You can override the amount of points by specifying a third element... something like:
x1 = linspace(0, pi/2, 300);
This creates 300 points. Play around with the third parameter. The more points you have, the more smooth the plot will be as the default method of plotting things in MATLAB is to just join the points together with straight lines.

How to plot a 3d graph of 2d fft transformations with a changing parameter

I want to make a 3d plot of 2d plots of function y
where y is the dft of function z with having as axis k(x) w0(y) and amplitude(y)(z), where k is the dft variable in frequency domain and w0 is a changing parameter between 0 and 4*pi/45.
n=(0:255);
x1 = exp(n.*(w1*1j));
x2 = 0.8.*exp(n*((w2-w0)).*1j);
z =hamming(256)*(x1+x2);
y = fft(abs(z))
If I'm interpreting your question properly, you wish to have something like this:
The x axis is the DFT number, the y axis is a parameter that changes your time-domain signal and z would be the magnitude of the FFT for each signal.
What you need to do is define a 2D grid of points where x is the number of FFT points you have... so in your case, that'll be 256 points, and the y axis defines your varying w0 term from 0 to 4*pi/45. The structure for this grid will be such that each row defines one DFT result.
For this, use ndgrid for that, and you do it the following way:
max_dft_number = 256;
num_w = 10;
[w0,n] = ndgrid(linspace(0,4*pi/45,num_w), 0:max_dft_number-1);
max_dft_number determines how many DFT numbers you want to compute. So in your case, that would be 256. You can vary that according to how many DFT numbers you want. num_w gives you how many w0 points you want between 0 to 4*pi/45, then linspace gives you a set of linearly spaced points from 0 to 4*pi/45 where we have num_w of these points. I set it to 10 here to give a good illustration.
Once you have this, simply use X and Y and substitute it into your code above. You don't define w1 and w2, so I'll assume it's constant:
w1 = 0.1; w2 = 0.2;
x1 = exp(n.*(w1*1j)); %// Change - vectorized
x2 = 0.8.*exp(n.*((w2-w0)).*1j); %// Change - vectorized
z = bsxfun(#times,hamming(max_dft_number).', x1+x2); %// Change - make sure hamming window applies over each row
y = abs(fft(z, [], 2)); %// Change - FFT first, then magnitude after. Apply to each row
I had to use bsxfun to apply the Hamming window on each row of x1 + x2. Remember, each row is a DFT result for a particular w0 parameter. I also had to transpose hamming(256) as the default output is a column. bsxfun in this case with the use of #times will duplicate the Hamming window coefficients so that every row gets multiplied by the same window. If you provide a matrix to fft, by default it applies the FFT over each column of a matrix. We don't want that, and we want to apply this to every row, and so you would need to do fft(z,[],2); to do that.
Now, to finally achieve your desired plot, all you have to do is use the waterfall function, which takes in a set 2D grid coordinates and the corresponding output in the z direction. It assumes that each row is an individual trace of a 3D function.... just like what you wanted.
So:
waterfall(n, w0, y);
xlabel('DFT number');
ylabel('w0');
zlabel('Magnitude');
colormap([0 0 0]); %// Make plot all black
view(-12,64); %// Adjust view for better look
We get:

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);

How to plot for loop results in matlab?

I am calculating the absolute error of a summation compared to an integral (summation answer - integral answer):
integral of e^x from 0 to 1, compared to (1/n)*summation(e^rand()) from i = 1 to n.
I have to plot the error vs n in matlab. I can't wrap my head around how to do this. I am able to calculate the error from 1 to an arbitrary number like 50 by using a for loop from 1 to 50. But, how would I plot this? I would need to do multiple summations to different values of n correct?
So what you want to do is calculate the area with the integral and the error function at the same time and store them in an array:
maxLevel = 50;
integral = zeros(maxLevel, 1);
summation = zeros(maxLevel, 1);
for i = 1:maxLevel
integral(i) = integralFunction(i);
summation(i) = summationFunction(i);
end
Then you can plot like this:
plot(1:length(integral), integral, 'r');
hold on;
plot(1:length(summation), summation, 'g');