MATLAB: How do I graph multiple functions on the same graph? - matlab

How can I graph multiple functions on the same graph/plot/Cartesian plane on MATLAB with domain and range restrictions?
For example I made up the following functions below. How would I graph the following on the same graph within MATLAB?
Function 1: x = -3 for 10 <= y <= 14
Function 2: y = -2x for -5 <= x <= -4
Function 3: (x-0)^2 + (y-12)^2 = 2.25 // Produces a circle
Function 4: y = 4 for -1 <= x <= 1

Matlab is a numerical computing environment, so you'll need to tell it what you're looking for while plotting.
In the case of your first example, you'll need to tell it which Y values to plot. Since X is always the same, you know it's going to be a line - so two points will be enough. Plot requires parallel arrays, so:
Function 1: x = [-3 -3]; y = [10 14]; plot(x, y);
To plot additional lines on the same graph, use the command hold on, which applies to the figure you just plotted. If you don't do this, new plot commands will erase the old plots.
Similarly,
Function 2: x = [-5 4]; y = -2*x; plot(x, y);
For circles/ellipses like #3, ezplot can be helpful, although you still have to specify the range.
Function 3: ezplot('x^2 + (y-12)^2 - 2.25', [-3,3,10,14])
The last one is easy, but let's say it were a curve instead. You'd want to plot more than just two x values. You can create a vector from a range like this: x = -1:0.1:1;, or an evenly space set of points from -1 to 1, with an interval of 0.1. Let's say you want to plot it on the same graph, and you've already done hold on. You want a different color, and you want to show the individual points that make up the line, you can use the third argument to the plot function:
Function 4: x = -1:0.1:1; y = 4 * ones(length(x)); plot(x, y, '-r.');
The second command here, y = 4 * ones(length(x)); simply creates a y vector that is the same length as 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,'-')

how i can plot a graph with inetger number as input

how i can plot cos(3 pi/7 * n ) such that n be integer number in interval [x=0,x=10] in matlab?
i used this code
figure
X = linspace(0,2*pi,10)';
Y = cos(X);
stem(X,Y)
set(gca,'xlim',[0,10])
the graph that i get is this , but i want to show points of graph in integer number of x axis . how can i do that ?
Instead of using linspace for such a simple example as this one, you can just define your vector X as an integer vector taking steps of 1, from 0 to 10:
figure
X = 0:1:10;
Y = cos(3*pi/7*X);
stem(X,Y)
set(gca,'xlim',[0,10])
Below shows the plot generated by the code snippet above (bottom plot) as well as the same plot using step size 0.5 (X = 0:0.5:10, top plot).
Note that as Adriaan notes in the comments below, the default step size for ... = from:stepsize:to notation is 1, i.e., if omitting the stepsize and simply writing ... = from:to, a step size of 1 is used by default (stepsize=1).

How do I create a plot that represents a sum of sinusoids without a loop?

How can I make a simple plot of function y = sin(x) + sin(3x) + ... + sin(100x) without using any loops?
Yes, it's possible by using a call to bsxfun to generate the right points to be applied per sinusoid, then using a sum call to sum all of the sinusoids for each point. You'd then plot this normally.
Something like this comes to mind:
x = -5:0.01:5; %// Define x points here
pts = bsxfun(#times, 1:2:101, x(:)); %// Generate a grid of points
y = sum(sin(pts), 2); %// Compute the y values for each x value
plot(x(:),y); %// Plot the result
The first line of code generates a set of x values that you wish to plot. The next line of code generates a 2D grid of points. Each row applies x, 3*x, 5*x, ..., 101*x for one particular point in x. Each column represents one unique x point. As such, when we use sum (next line), we also apply the sin operator to each of these individual points on the grid, then go ahead and sum over each row to produce the output for each unique point of x. We then plot the results.
Note that I used x(:) to unroll the x vector so that it's a column vector. This is needed for the code to work. This also allows you to make x a row or column vector and the code will still work.
This is the plot I get:
Use cumsum.
octave:1> x = 1;
octave:2> sin(x)
ans = 0.841470984807897
octave:3> sin(x*1)
ans = 0.841470984807897
octave:4> sin(x*1) + sin(x*2)
ans = 1.75076841163358
octave:5> sin(x*1) + sin(x*2) + sin(x*3)
ans = 1.89188841969345
octave:6> cumsum(sin(x * (1:3)))
ans =
0.841470984807897 1.75076841163358 1.89188841969345

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 do you draw a line between points in matlab?

I'm looking to create a "web" between a set of points where the data tells whether there is a link between any two points.
The way I thought of would be by plotting every couple points, and overlaying each couple on top of eachother.
However, if there is a way to just simple draw a line between two points that would be much easier.
Any help would be appreciated!
If you can organize the x and y coordinates of your line segments into 2-by-N arrays, you can use the function PLOT to plot each column of the matrices as a line. Here's a simple example to draw the four lines of a unit square:
x = [0 1 1 0; ...
1 1 0 0];
y = [0 0 1 1; ...
0 1 1 0];
plot(x,y);
This will plot each line in a different color. To plot all of the lines as black, do this:
plot(x,y,'k');
Use plot. Suppose your two points are a = [x1 y1] and b = [x2 y2], then:
plot([x1 x2],[y1 y2]);
If you meant by I'm looking to create a "web" between a set of points where the data tells whether there is a link between any two points actually some kind of graph represented by its adjacency matrix (opposite to other answers simple means to connect points), then:
this gplot function may indeed be the proper tool for you. It's the basic visualization tool to plot nodes and links of a graph represented as a adjacency matrix.
use this function:
function [] = drawline(p1, p2 ,color)
%enter code here
theta = atan2( p2(2) - p1(2), p2(1) - p1(1));
r = sqrt( (p2(1) - p1(1))^2 + (p2(2) - p1(2))^2);
line = 0:0.01: r;
x = p1(1) + line*cos(theta);
y = p1(2) + line*sin(theta);
plot(x, y , color)
call it like:
drawline([fx(i) fy(i)] ,[y(i,1) y(i,2)],'red')
Credit: http://www.mathworks.com/matlabcentral/answers/108652-draw-lines-between-points#answer_139175
Lets say you want a line with coordinates (x1,y1) and (x2,y2). Then you make a vector with the x and y coordinates: x = [x1 x2] and y=[y1 y2].
Matlab has a function called 'Line', this is used in this way:
line(x,y)
If you want to see the effect of drawing lines, you can use plot inside for loop note that data is a n*2 matrix containing the 'x,y' of 'n' points
clf(figure(3))
for i = 1 : length(data)-1
plot([data(i,1),data(i+1,1)], [data(i,2),data(i+1,2)], '-*');
hold on
end
hold off
Or can use this statement to draw it in one step
plot(data(:,1), data(:,2), '-*');