MATLAB - Plotting multiple graphs - matlab

I am new to MATLAB and am having difficulty plotting multiple graphs. Here are my vectors to graph:
S = [1.2421
2.3348
0.1326
2.3470
6.7389
3.7089
11.8534
-1.8708
...]
Y = [1.1718
1.8824
0.3428
2.1057
1.6477
2.3624
2.1212
-0.7971
...]
w = [0.1753
0.3277]
S is my training data and Y is my output vector. Then I add a column vector to my training data:
O = ones(length(S), 1)
X = [S 0]
w = inv(X'*X)*X'*Y
So I am trying to plot X, Y and w on the same graph. I plot w first, hold, X and this is where I get lost. Basically they are not on the same scale because the size of x is much less than X (X and Y are both vectors of size 100 and w is of size 2).
plot(w)
Then I do:
hold
plot(X)
Now the w that I plotted is so small compared to the plot of X. How would I make them the same scale? Also maybe making them a different color?

plotyy will create the figure you are looking for. See the examples in the link for further plot customization.

I'd just comment, but I don't have enough reputation... If you are not aiming to present the data, but just be able to visualize it, you can rescale your datasets and avoid the not-so-easy-to-work-with plotyy (although it is the best answer):
W = W/max(W);
X = X/max(X);
plot(W)
hold on
plot(X)
For additional formating of the plots, see mathworks polt. There you can change color, linewidth and whatnot.

Related

MATLAB - 3D volume fill based on inequalities

I have three variables x, y and z. I have inequalities of the form
x >= a, y>= b, z>=c, x+y>=d, y+z>=e, x+z>=f, x+y+z>=g
where a to g are positive numbers. On a 3D plot with axes x, y and z, this is an open volume. I would like to fill the open side (i.e. away from 0) shape with color and show it in a plot. What is the way to do this on MATLAB?
I attempted to use fill3 and a mesh but the result was not very good
[x,y,z] = meshgrid(0:0.01:2,0:0.01:2,0:0.01:2);
ineq = (x>=1)& (y>0.5)&(z>=0.25)&(x+y>1.25)&(y+z>0.6)&(x+z>1.1)&(x+y+z>1.6);
fill3(x(:),y(:),z(:), 'r')
box on
grid on
Using plot3 also was not very good. Is there any other way to generate a nice 3D figure on MATLAB?
Mathematica does this using RegionPlot3D. I was hoping for a similar resultant image.
First of all, be careful when using 3D meshes, the one you defined contains 8M+ points.
Assuming your shape is convex, you can use convhull and trisurf:
Not that the option 'Simplify' is set as true to reduce the number of elements accounted for in the convex hull.
[x,y,z] = meshgrid(0:0.1:2,0:0.1:2,0:0.1:2);
ineq = (x>=1)& (y>0.5)&(z>=0.25)&(x+y>1.25)&(y+z>0.6)&(x+z>1.1)&(x+y+z>1.6);
figure;
x_ineq = x(ineq);
y_ineq = y(ineq);
z_ineq = z(ineq);
id_cvhl = convhull(x_ineq,y_ineq,z_ineq,'Simplify',true);
trisurf(id_cvhl,x_ineq,y_ineq,z_ineq,'FaceColor','cyan','edgecolor','none')
xlim([0 2])
ylim([0 2])
zlim([0 2])
In case you want the result to look a bit more than RegionPlot3D, don't use Simplify, and plot the edges (Be careful not too have a mesh with too many points!).
id_cvhl = convhull(x_ineq,y_ineq,z_ineq);
trisurf(id_cvhl,x_ineq,y_ineq,z_ineq,'Facecolor','yellow')

how to plot graphs above each other in matlab [duplicate]

I wanted to generate a plot (X vs Y), and Z values depend on the Y. The example is shown in the figure below. The matrix size of X is same with Z but not Y. I can plot Z against X, but I wanted to combine all the plot into a single plot and become Y against X. I can plot multiple plots into a single plot but the plot is overlapping each other.
My question is there any method I can merge multiple plots into a single plot without overlapping each plot as the difference between each plot is very small (e.g Z1=1,2,3,4,5 and Z2=1.0001,2.0002,3.0001,4.0002,5.0001). So, I wanted to set each Z plot at different Y axis. (e.g Z1 at Y=0, Z2 at Y=2 ...)
Does anyone have any suggestions or idea?
Thank You
I'll clarify the ideas I wrote in a comment.
First, let's get some data:
x = 470:0.1:484;
z1 = cos(x)/2;
z2 = sin(x)/3;
z3 = cos(x+0.2)/2.3;
I'll plot just three data sets, all of this is trivial to extend to any number of data sets.
Idea 1: multiple axes
The idea here is simply to use subplot to create a small-multiple type plot:
ytick = [-0.5,0.0,0.5];
ylim = [-0.9,0.9]);
figure
h1 = subplot(3,1,1);
plot(x,z1);
set(h1,'ylim',ylim,'ytick',ytick);
title('z1')
h2 = subplot(3,1,2);
plot(x,z2);
set(h2,'ylim',ylim,'ytick',ytick);
title('z2')
h3 = subplot(3,1,3);
plot(x,z3);
set(h3,'ylim',ylim,'ytick',ytick);
title('z3')
Note that it is possible to, e.g., remove the tick labels from the top two plot, leaving only labels on the bottom one. You can then also move the axes so that they are closer together (which might be necessary if there are lots of these lines in the same plot):
set(h1,'xticklabel',[],'box','off')
set(h2,'xticklabel',[],'box','off')
set(h3,'box','off')
set(h1,'position',[0.13,0.71,0.8,0.24])
set(h2,'position',[0.13,0.41,0.8,0.24])
set(h3,'position',[0.13,0.11,0.8,0.24])
axes(h1)
title('')
ylabel('z1')
axes(h2)
title('')
ylabel('z2')
axes(h3)
title('')
ylabel('z3')
Idea 2: same axes, plot with offset
This is the simpler approach, as you're dealing only with a single axis. #Zizy Archer already showed how easy it is to shift data if they're all in a single 2D matrix Z. Here I'll just plot z1, z2+2, and z3+4. Adjust the offsets to your liking. Next, I set the 'ytick' property to create the illusion of separate graphs, and set the 'yticklabel' property so that the numbers along the y-axis match the actual data plotted. The end result is similar to the multiple axes plots above, but they're all in a single axes:
figure
plot(x,z1);
hold on
plot(x,z2+2);
plot(x,z3+4);
ytick = [-0.5,0.0,0.5];
set(gca,'ytick',[ytick,ytick+2,ytick+4]);
set(gca,'yticklabel',[ytick,ytick,ytick]);
text(484.5,0,'z1')
text(484.5,2,'z2')
text(484.5,4,'z3')
The simplest would be to shift Z data. But note that Z2 would look like to be oscillating around 1 - so this is a neat visual representation, but might mislead.
% Simple version - shift Z curves by 0, 1, ... (as recommended by #Cris Luengo)
shiftMat = repmat(0 : size(Z, 2)-1, size(Z,1), 1);
Z = Z + shiftMat;
%Min shift up to have non-overlapping - curves touching
for i = 2 : size(Z, 2)
Zdif = (Z(:, i-1) - Z(:, i));
Z(:, i) = Z(:, i) + max(Zdif); % + 0.01 to separate them a little bit.
end
%Bigger shift up, to have all points of Z(2) equal or above all points of z1.
for i = 2 : numZ
Zdif = max(Z(:, i-1))-min(Z(:, i));
Z(:, i) = Z(:, i) + Zdif;
end
Another possibility is to have multiple Y axis and each Z curve plotted against its own Y axis. This is likely fancier and shouldn't mislead, but it is way more work, even after you grab the function, as you still need to position all those axes. MATLAB by default lets you use only 2 axes, so grab a function from fileexchange to add more: https://www.mathworks.com/matlabcentral/fileexchange/9016-addaxis

Matlab- Given matrix X with xi samples, y binary column vector, and a vector w plot all these into 3d graph

I have started to learn Machine Learning, and programming in matlab.
I want to plot a matrix sized m*d where d=3 and m are the number of points.
with y binary vector I'd like to color each point with blue/red.
and plot a plane which is described with the vertical vector to it w.
The problem I trying to solve is to give some kind of visual representation of the data and the linear predictor.
All I know is how to single points with plot3, but no any number of points.
Thanks.
Plot the points using scatter3()
scatter3(X(y,1),X(y,2),X(y,3),'filled','fillcolor','red');
hold on;
scatter3(X(~y,1),X(~y,2),X(~y,3),'filled','fillcolor','blue');
or using plot3()
plot(X(y,1),X(y,2),X(y,3),' o','MarkerEdgeColor','red','MarkerFaceColor','red');
hold on;
plot(X(~y,1),X(~y,2),X(~y,3),' o','MarkerEdgeColor','blue','MarkerFaceColor','blue');
There are a few ways to plot a plane. As long as w(3) isn't very close to 0 then the following will work okay. I'm assuming your plane is defined by x'*w+b=0 where b is a scalar and w and x are column vectors.
x1min = min(X(:,1)); x2min = min(X(:,2));
x1max = max(X(:,1)); x2max = max(X(:,2));
[x1,x2] = meshgrid(linspace(x1min,x1max,20), linspace(x2min, x2max, 20));
x3 = -(w(1)*x1 + w(2)*x2 + b)/w(3);
surf(x1,x2,x3,'FaceColor',[0.6,0.6,0.6],'FaceAlpha',0.7,'EdgeColor',[0.4,0.4,0.4],'EdgeAlpha',0.4);
xlabel('x_1'); ylabel('x_2'); zlabel('x_3'); axis('vis3d');
Resulting plot

Draw a line with non-Cartesian coordinates in MATLAB

MATLAB's surf command allows you to pass it optional X and Y data that specify non-cartesian x-y components. (they essentially change the basis vectors). I desire to pass similar arguments to a function that will draw a line.
How do I plot a line using a non-cartesian coordinate system?
My apologies if my terminology is a little off. This still might technically be a cartesian space but it wouldn't be square in the sense that one unit in the x-direction is orthogonal to one unit in the y-direction. If you can correct my terminology, I would really appreciate it!
EDIT:
Below better demonstrates what I mean:
The commands:
datA=1:10;
datB=1:10;
X=cosd(8*datA)'*datB;
Y=datA'*log10(datB*3);
Z=ones(size(datA'))*cosd(datB);
XX=X./(1+Z);
YY=Y./(1+Z);
surf(XX,YY,eye(10)); view([0 0 1])
produces the following graph:
Here, the X and Y dimensions are not orthogonal nor equi-spaced. One unit in x could correspond to 5 cm in the x direction but the next one unit in x could correspond to 2 cm in the x direction + 1 cm in the y direction. I desire to replicate this functionality but drawing a line instead of a surf For instance, I'm looking for a function where:
straightLine=[(1:10)' (1:10)'];
my_line(XX,YY,straightLine(:,1),straightLine(:,2))
would produce a line that traced the red squares on the surf graph.
I'm still not certain of what your input data are about, and what you want to plot. However, from how you want to plot it, I can help.
When you call
surf(XX,YY,eye(10)); view([0 0 1]);
and want to get only the "red parts", i.e. the maxima of the function, you are essentially selecting a subset of the XX, YY matrices using the diagonal matrix as indicator. So you could select those points manually, and use plot to plot them as a line:
Xplot = diag(XX);
Yplot = diag(YY);
plot(Xplot,Yplot,'r.-');
The call to diag(XX) will take the diagonal elements of the matrix XX, which is exactly where you'll get the red patches when you use surf with the z data according to eye().
Result:
Also, if you're just trying to do what your example states, then there's no need to use matrices just to take out the diagonal eventually. Here's the same result, using elementwise operations on your input vectors:
datA = 1:10;
datB = 1:10;
X2 = cosd(8*datA).*datB;
Y2 = datA.*log10(datB*3);
Z2 = cosd(datB);
XX2 = X2./(1+Z2);
YY2 = Y2./(1+Z2);
plot(Xplot,Yplot,'rs-',XX2,YY2,'bo--','linewidth',2,'markersize',10);
legend('original','vector')
Result:
Matlab has many built-in function to assist you.
In 2D the easiest way to do this is polar that allows you to make a graph using theta and rho vectors:
theta = linspace(0,2*pi,100);
r = sin(2*theta);
figure(1)
polar(theta, r), grid on
So, you would get this.
There also is pol2cart function that would convert your data into x and y format:
[x,y] = pol2cart(theta,r);
figure(2)
plot(x, y), grid on
This would look slightly different
Then, if we extend this to 3D, you are only left with plot3. So, If you have data like:
theta = linspace(0,10*pi,500);
r = ones(size(theta));
z = linspace(-10,10,500);
you need to use pol2cart with 3 arguments to produce this:
[x,y,z] = pol2cart(theta,r,z);
figure(3)
plot3(x,y,z),grid on
Finally, if you have spherical data, you have sph2cart:
theta = linspace(0,2*pi,100);
phi = linspace(-pi/2,pi/2,100);
rho = sin(2*theta - phi);
[x,y,z] = sph2cart(theta, phi, rho);
figure(4)
plot3(x,y,z),grid on
view([-150 70])
That would look this way

Computing and plotting pdf of U as a function of two uniformly distributed random variables

I am working on a joint pdf problem in which the random variable
U = sqrt(X^2+Y^2)
X and Y are uniformly distributed over (-2,2). I want to plot joint pdf of X and Y. Then compute pdf of U and plot it as well. I am using matlab R2011a, and so far, I have come up with the following code. On running the code I got an error message
Undefined function or method 'makedist' for input arguement type 'char'.
I found out that makedist is not on 2011 version. So I tried using
a=-2;
b=2;
X=a+(b-a)*rand(-10,10);
Y= a+(b-a)*rand(-10,10).
However, I am not sure how to compute pdfs of X and Y, and then joint pdf of XY from this. Any help, partial or holistic, is appreciated.
Here is the matlab code for the problem
%% Create distribution objects for X~U(-2,2) and Y~U(-2,2)
pdx=makedist('Uniform','lower',-2,'upper',2);
pdy=makedist('Uniform','lower',-2,'upper',2);
%Compute the pfs
x_ref=-10:1:10;
y_ref=-10:1:10;
pdf_x=pdf(pdx,x_ref);
pdf_y=pdf(pdy,y_ref);
% Plot the pdfs
figure 1;
stairs(x_ref,pdf_x,'g','Linewidth',2);
hold on;
stairs(y_ref,pdf_y,'r','Linewidth',2);
ylim([0 1.5]);
hold off;
% Joint pdf of x and Y
pdfXY=pdf_x*pdf_y;
figure 2;
plot(pdfXY);
%CDF and PDF of U
U=sqrt(X^2+Y^2);
Umin=0;
Umax=sqrt(b^2+b^2);
a=lower;
b=upper;
x=sqrt(U^2-Y^2);
xmin=0;
xmax=x;
ymin=0;
ymax=U;
Ucdf=integral2(pdfXY,xmin,xmax,ymin,ymax);
% plot CDF of U
figure 3;
plot(Ucdf)
I am just looking to plot the regions than for any specific sample set. X and Y are continuous independent uniform random variables.
As your x and y are independent at random, the theoretical joint distribution is just a product of the two
P(x,y) = P(x)*P(y)
In terms of MATLAB code, you may think of x and y running along two different dimensions:
N = 10; %// think of a probability mass function over N points
x = linspace(-2,2, N);
y = linspace(-2,2, N)';
Px = ones(N,1)./N;
Py = ones(1,10)./N;
%// Then the joint will be:
Jxy = bsxfun(#times, Px , Py);
figure
pcolor(x,y,Jxy)
You can now plug whatever distribution you like, if they are independent for Px and Py, and it will work