Cumulative histogram - matlab

I have a function y=f(x), and I would like to plot in Matlab a histogram where I have the sum of ys for x in[n,n+1).
Is there a function in Matlab doing that automatically?

cumtrapz
http://www.mathworks.com/help/techdoc/ref/cumtrapz.html
Example:
x = linspace(0, pi, 30);
y = cos(x);
yint = cumtrapz(x, y);
plot(x, yint, 'x');
hold on;
% exact integral
plot(x, sin(x), '-');

Related

Multiple colors in the same line

I would like to plot a sine curve in Matlab. But I want it blue for the positive values and red for the negative values.
The following code just makes everything red...
x = [];
y = [];
for i = -180 : 180
x = [x i];
y = [y sin(i*pi/180)];
end
p = plot(x, y)
set(p, 'Color', 'red')
Plot 2 lines with different colours, and NaN values at the positive/negative regions
% Let's vectorise your code for efficiency too!
x = -pi:0.01:pi; % Linearly spaced x between -pi and pi
y = sin(x); % Compute sine of x
bneg = y<0; % Logical array of negative y
y_pos = y; y_pos(bneg) = NaN; % Array of only positive y
y_neg = y; y_neg(~bneg)= NaN; % Array of only negative y
figure; hold on; % Hold on for multiple plots
plot(x, y_neg, 'b'); % Blue for negative
plot(x, y_pos, 'r'); % Red for positive
Output:
Note: If you're happy with scatter plots, you don't need the NaN values. They just act to break the line so you don't get join-ups between regions. You could just do
x = -pi:0.01:pi;
y = sin(x);
bneg = y<0;
figure; hold on;
plot(x(bneg), y(bneg), 'b.');
plot(x(~bneg), y(~bneg), 'r.');
Output:
This is so clear because my points are only 0.01 apart. Further spaced points would appear more like a scatter plot.

Plotting x,y,z with intervals

How do I plot xyz In rectangular, polar, and 3-D?
for x = 0 to 35pi:
Y = x*sin(x)
Z = x*cos(x)
Using the the intervals of X which provides very smooth plots . Create three plots including tittle and labels .
This is the input I have put in so far. I'm not sure if this is correct:
x = pi*linspace(0,35);
y = pi*x,sin(pi*x);
z = pi*x,cos(pi*x);
plot3(x,y,z)
title('data analysis')
xlabel('independent x')
ylabel('dependent y')
zlabel('z')
I believe this solves the problem as you describe it:
x = linspace(0, 35*pi, 10000);
y = x .* sin(x);
z = x .* cos(x);
plot3(x, y, z);
title('data analysis');
xlabel('independent x');
ylabel('dependent y');
zlabel('z');

4D plot (3D+color) from 4 row vectors

I have 4 row vectors x, y, z and s, all of them have equal sizes 1*size. x, y, z should be the three Cartesian corodinate axes and s should be represented by colors (I want figure like below image). The statement Surf does not accept row vectors. I have read several stackoverflow post, but I could not find the answer. How can I plot such a figure?
I really appreciate any help you can provide.
I can't test it because you didn't provide any data, but you could try:
trisurf(x,y,z,s)
If that doesn't work then try:
DT = delaunayTriangulation(x,y,z);
tetramesh(DT,s);
You can try with this example of a 3D cube for a 3D meshgrid and it plots the "temperature".
L = 1;
dx = 0.25;
dy = dx;
dz = dy;
Nx = L/dx; Ny = Nx; Nz = Ny;
x = dx/2:dx:L-dx/2;
y = x; z = y;
[xx, yy, zz] = meshgrid(x,y,z);
theta = NaN(size(zz));
for jj=1:4;
for ii=1:4
for kk=1:4
theta(jj,ii,kk) = 273.15 + 5.*random('normal', 0, 1)
end
end
end
clf
isosurface(xx, yy, zz, theta)
colorbar
colormap jet
[fe, ve, ce] = isocaps(x, y, z, theta, 10);
p2 = patch('Faces', fe, 'Vertices', ve, 'FaceVertexCData', ce);
p2.FaceColor = 'interp';
p2.EdgeColor = 'none' ;
grid on
xlabel('X (m)');
ylabel('Y (m)');
zlabel('Z (m)');
title('Temperatures');
set(gca, 'clim', [273.15 273.15+5])
set(get(colorbar, 'title'), 'string', 'K', 'FontW', 'bold', 'fontname', 'Times New Roman', 'fontsize', 14);
view(3)

Fit bimodal normal distribution to a vector of values, not its histogram

I would like to fit a bimodal normal distribution to data that looks bimodally distributed, such as the example below (plot(x)):
From the MATLAB docs I thought about using the mle function with a function handle to a mixture of two Gaussians:
#(x,p,mu1,mu2,sigma1,sigma2)p*normpdf(x,mu1,sigma1)+(1-p)*normpdf(x,mu2,sigma2)
However, the mle function fits to the histogram of x, while I want an approximation to x itself. How could I achieve this?
The idea is to create array y whose histogram looks like your function x (which should be positive everywhere):
%// Calculate
N = numel(x);
xi = fix(x/max(x)*100); % Limit the memory damage
yp = arrayfun(#(n) n*ones(1,xi(n)), 1:N, 'UniformOutput', false);
y = [yp{:}];
%// Visually inspect
ax = axes('Parent', figure());
plot(ax, xi); hold(ax, 'on');
hist(ax, y, N);
Matlab has a builtin bimodal fit
f =#(A,m,s,x) A(1) * exp(-((x-m(1))/s(1)).^2) + A(2) * exp(-((x-m(2))/s(2)).^2);
g =#(x) f([5, 10], [1, 10], [3, 5], x);
x = (-20:0.01:20)';
y = g(x) + 0.25*(rand(size(x)) - 0.5);
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
[fitresult, gof] = fit( x, y, 'gauss2', opts );
plot( fitresult, x, y );
%u can use the function
histfit(yourdata,nbins,'Kernel','normal');
%sometimes the it doesnt converge ; in those case u can resort to distributionFitter app
distributionFitter(yourdata);
%select non-parametric ; then normal

How can I plot a function with two variables in Octave or Matlab?

I want to use Octave to plot fairly simple functions with two variables like: f(x,y) = x^2 + 3y . It is very easy to plot single variable functions, but I am having a lot of trouble finding out how to do two variable functions. Does anyone know the best way of doing this?
Plotting a function of two variables would normally mean a 3-dimensional plot - in MATLAB you would use the function plot3 for that. To plot your function f(x,y) in the interval [-10,10] for both X and Y, you could use the following commands:
x = [-10:.1:10];
y = [-10:.1:10];
plot3(x, y, x.^2 + 3*y)
grid on
In case it may help someone out there... I ran in Octave the code in the accepted answer and I got this plot:
But I really wanted the function for every point in the Cartesian product of x and y, not just along the diagonal, so I used the function mesh to get this 3D plot with the projected contour lines in the x,y plane:
x = [-10:.1:10];
y = [-10:.1:10];
[xx, yy] = meshgrid (x, y);
z = xx.^2 + 3*yy;
mesh(x, y, z)
meshc(xx,yy,z)
xlabel ("x");
ylabel ("y");
zlabel ("f(x,y)");
title ("f(x,y) = x^2 + 3y");
grid on
To get rid of the mesh-wire texture of the plot, the function surf did the trick:
x = [-10:.1:10];
y = [-10:.1:10];
[xx, yy] = meshgrid (x, y);
z = xx.^2 + 3*yy;
h = surf(xx,yy,z);
colormap hsv;
set(h,'linestyle','none');
xlabel ("x");
ylabel ("y");
zlabel ("f(x,y)");
title ("f(x,y) = x^2 + 3y");
Another way to plot is as a heatmap with contour lines:
x = [-10:.1:10];
y = [-10:.1:10];
[xx, yy] = meshgrid (x, y);
z = xx.^2 + yy.*3;
contourf(xx,yy,z);
colormap hsv;
xlabel ("x");
ylabel ("y");
zlabel ("f(x,y)");
title ("f(x,y) = x^2 + 3y");
grid on
And for completeness, the levels can be labeled:
x = [-10:.1:10];
y = [-10:.1:10];
[xx, yy] = meshgrid (x, y);
z = xx.^2 + 3*yy;
[C,h] = contour(xx,yy,z);
clabel(C,h)
xlabel ("x");
ylabel ("y");
zlabel ("f(x,y)");
title ("f(x,y) = x^2 + 3y");
grid on
In addition to the excellent answers from #Toni and #esskov, for future plotters of functions with two variables, the contour and contourf functions are useful for some applications.
MATLAB Code (2018b):
x = [-10:.1:10];
y = [-20:.1:20];
[xx, yy] = meshgrid (x, y);
z = xx.^2 + 3*yy; % Borrowed 4 lines from #Toni
figure
s(1) = subplot(1,2,1), hold on % Left Plot
[M,c] = contour(xx,yy,z); % Contour Plot
c.ShowText = 'on'; % Label Contours
c.LineWidth = 1.2; % Contour Line Width
xlabel('X')
ylabel('Y')
box on
s(2) = subplot(1,2,2), hold on % Right Plot
[M2,c2] = contourf(xx,yy,z);
colorbar % Add Colorbar
xlabel('X')
ylabel('Y')
box on
title(s(1),'Contour Plot')
title(s(2),'Filled Contour Plot')
Update: Added example of surfc
h = surfc(xx,yy,z)