Plotting histogram side by side in Matlab - matlab

I have two vectors, c and d, whose histogram I need to plot side by side in the same figure in matlab. when i do
hist(c);
hold on;
hist(d)
the scale changes and I cant see the histogram of c vector. Where am i going wrong? Any help will be appreciated.

If you want the two to be in the same figure, you could try adjusting the X and Y limits to suit your needs (try help xlim and help ylim). However plotting them in the same figure might not always suit your needs, as a particular plot has to of course maintain a certain limit for X and Y.
If displaying them side by side in different figures would suffice however, you could consider using subplot():
>> A=[1 1 1 2 2];
>> B=[1 2 2 2 2];
>> figure(1);
>> hold on;
>> subplot(1,2,1);
>> hist(A);
>> subplot(1,2,2);
>> hist(B);
Resultant figure:
Notice how the different axis limits are maintained.

You can use axis([xmin xmax ymin ymax]) to control the x and y axis and select a range that will display both histograms. Depending on what you want your plot to look like, you may also want to try using nelements = hist(___) to get the number of elements in each bin and then plot them using bar(x,nelements) to control the location of each bar.

hist assumes you want to divide the range into 10 equal sized bins by default. If you want to use the same bins for both histograms, first find the range of your values and make a set of bin centers (e.g. binCenters = linspace(min(x), max(x), 15)'), then callhist(x, binCenters)`.

I use MATLAB histograms quite frequently and have wrote this small matlab script to plot two histograms (first one red and second blue) in one figure. The script is quite simple but the important thing is that the histograms should be comparable (i.e. equally spaced frequency bins).
function myhist(varargin)
% myhist function to plot the histograms of x1 and x2 in a single figure.
% This function uses the same xvalue range and same bins to plot the
% histograms, which makes comparison possible.
if nargin<2
x1 = cell2mat(varargin(1));
x2 = x1;
res = 100;
elseif nargin==2
x1 = cell2mat(varargin(1));
if length(cell2mat(varargin(2)))==1
res = cell2mat(varargin(2));
x2 = x1;
else
x2 = cell2mat(varargin(2));
res = 100;
end
elseif nargin>2
x1 = cell2mat(varargin(1));
x2 = cell2mat(varargin(2));
res = cell2mat(varargin(3));
end
if numel(x1)~=length(x1) || numel(x2)~=length(x2)
error('Inputs must be vectors.')
return
end
xrangel = max(min(x1),min(x2));
xrangeh = min(max(x1),max(x2));
x1_tmp = x1(x1>=xrangel & x1<=xrangeh);
x2_tmp = x2(x2>=xrangel & x2<=xrangeh);
xbins = xrangel:(xrangeh - xrangel)/res:xrangeh;
hist(x1_tmp,xbins)
hold on
h = findobj(gca,'Type','patch');
set(h,'FaceColor','r','EdgeColor','w');
hist(x2_tmp,xbins)

Related

Producing a histogram in Matlab with out using Hist

I am using histograms in Matlab to look at the distribution of some data from my experiments. I want to find the mean distribution (mean height of the bars) from a group of tests then produce an average histogram.
By using this code:
data = zeros(26,31);
for i = 1:length(files6)
x = csvread(files6(i).name);
x = x(1:end,:);
time = x(:,1);
variable = x(:,3);
thing(:,1) = x(:,1);
thing(:,2) = x(:,3);
figure()
binCenter = {0:tbinstep:tbinend 0:varbinstep:varbinend};
hist3(thing, 'Ctrs', binCenter, 'CDataMode','auto','FaceColor','interp');
colorbar
[N,C] = hist3(thing, 'Ctrs', binCenter);
data = data + N;
clearvars x time variable
end
avedata = data / i;
I can find the mean of N, which will be the Z value for the plot (histogram) I want, and I have X,Y (which are the same for all tests) from:
x = 0:tbinstep:tbinend;
y = 0:varbinstep:varbinend;
But how do I bring these together to make the graphical out that shows the average height of the bars? I can't use hist3 again as that will just calculate the distribution of avedata.
AT THE RISK OF STARTING AN XY PROBLEM using bar3 has been suggested, but that asks the question "how do I go from 2 vectors and a matrix to 1 matrix bar3 can handle? I.e. how do I plot x(1), y(1), avedata(1,1) and so on for all the data points in avedata?"
TIA
By looking at hist3 source code in matlab r2014b, it has his own plotting implemented inside that prepares data and plot it using surf method. Here is a function that reproduce the same output highly inspired from the hist3 function with your options ('CDataMode','auto','FaceColor','interp'). You can put this in a new file called hist3plot.m:
function [ h ] = hist3plot( N, C )
%HIST3PLOT Summary of this function goes here
% Detailed explanation goes here
xBins = C{1};
yBins = C{2};
% Computing edges and width
nbins = [length(xBins), length(yBins)];
xEdges = [0.5*(3*xBins(1)-xBins(2)), 0.5*(xBins(2:end)+xBins(1:end-1)), 0.5*(3*xBins(end)-xBins(end-1))];
yEdges = [0.5*(3*yBins(1)-yBins(2)), 0.5*(yBins(2:end)+yBins(1:end-1)), 0.5*(3*yBins(end)-yBins(end-1))];
xWidth = xEdges(2:end)-xEdges(1:end-1);
yWidth = yEdges(2:end)-yEdges(1:end-1);
del = .001; % space between bars, relative to bar size
% Build x-coords for the eight corners of each bar.
xx = xEdges;
xx = [xx(1:nbins(1))+del*xWidth; xx(2:nbins(1)+1)-del*xWidth];
xx = [reshape(repmat(xx(:)',2,1),4,nbins(1)); NaN(1,nbins(1))];
xx = [repmat(xx(:),1,4) NaN(5*nbins(1),1)];
xx = repmat(xx,1,nbins(2));
% Build y-coords for the eight corners of each bar.
yy = yEdges;
yy = [yy(1:nbins(2))+del*yWidth; yy(2:nbins(2)+1)-del*yWidth];
yy = [reshape(repmat(yy(:)',2,1),4,nbins(2)); NaN(1,nbins(2))];
yy = [repmat(yy(:),1,4) NaN(5*nbins(2),1)];
yy = repmat(yy',nbins(1),1);
% Build z-coords for the eight corners of each bar.
zz = zeros(5*nbins(1), 5*nbins(2));
zz(5*(1:nbins(1))-3, 5*(1:nbins(2))-3) = N;
zz(5*(1:nbins(1))-3, 5*(1:nbins(2))-2) = N;
zz(5*(1:nbins(1))-2, 5*(1:nbins(2))-3) = N;
zz(5*(1:nbins(1))-2, 5*(1:nbins(2))-2) = N;
% Plot the bars in a light steel blue.
cc = repmat(cat(3,.75,.85,.95), [size(zz) 1]);
% Plot the surface
h = surf(xx, yy, zz, cc, 'CDataMode','auto','FaceColor','interp');
% Setting x-axis and y-axis limits
xlim([yBins(1)-yWidth(1) yBins(end)+yWidth(end)]) % x-axis limit
ylim([xBins(1)-xWidth(1) xBins(end)+xWidth(end)]) % y-axis limit
end
You can then call this function when you want to plot outputs from Matlab's hist3 function. Note that this can handle non uniform positionning of bins:
close all; clear all;
data = rand(10000,2);
xBins = [0,0.1,0.3,0.5,0.6,0.8,1];
yBins = [0,0.1,0.3,0.5,0.6,0.8,1];
figure()
hist3(data, {xBins yBins}, 'CDataMode','auto','FaceColor','interp')
title('Using hist3')
figure()
[N,C] = hist3(data, {xBins yBins});
hist3plot(N, C); % The function is called here
title('Using hist3plot')
Here is a comparison of the two outputs:
So if I understand your question and code correctly, you are plotting the distribution of multiple experiments' data as histograms, then you want to calculate the average shape of all the previous histograms.
I usually avoid giving approaches the asker isn't explicitly asking for, but for this one I must comment that it is a very strange thing to do. I've never heard of calculating the average shape of multiple histograms before. So just in case, you could simply append all your experiment's data into a single variable, and plot a normalized histogram of that using histogram2. This code outputs a relative frequency histogram. (Other normalization methods)
% Append all data in a single matrix
x = []
for i = 1:length(files6)
x = [x; csvread(files6(i).name)];
end
% Plot normalized bivariate histogram, normalized
xEdges = 0:tbinstep:tbinend;
yEdges = 0:varbinstep:varbinend;
histogram2(x(:,1), x(:,3), xEdges, yEdges, 'Normalize', 'Probability')
Now, if you really are looking to draw the average shape of multiple histograms, then yes, use bar3. Since bar3 doesn't accept an (x,y) value argument, you can follow the other answer, or modify the XTickLabel and YTickLabel property to match whatever your bin range is, afterwards.
... % data = yourAverageData;
% Save axis handle to `h`
h = bar3(data);
% Set property of axis
h.XTickLabels = 0:tbinstep:tbinend;
h.YTickLabels = 0:varbinstep:varbinend;

Plotting the implicit function x+y - log(x) - log(y) -2 = 0 on MATLAB

I wanted to plot the above function on Matlab so I used the following code
ezplot('-log(x)-log(y)+x+y-2',[-10 10 -10 10]);
However I'm just getting a blank screen. But clearly there is at least the point (1,1) that satisfies the equation.
I don't think there is a problem with the plotter settings, as I'm getting graphs for functions like
ezplot('-log(y)+x+y-2',[-10 10 -10 10]);
I don't have enough rep to embed pictures :)
If we use solve on your function, we can see that there are two points where your function is equal to zero. These points are at (1, 1) and (0.3203 + 1.3354i, pi)
syms x y
result = solve(-log(x)-log(y)+x+y-2, x, y);
result.x
% -wrightOmega(log(1/pi) - 2 + pi*(1 - 1i))
% 1
result.y
% pi
% 1
If we look closely at your function, we can see that the values are actually complex
[x,y] = meshgrid(-10:0.01:10, -10:0.01:10);
values = -log(x)-log(y)+x+y-2;
whos values
% Name Size Bytes Class Attributes
% values 2001x2001 64064016 double complex
It seems as though in older versions of MATLAB, ezplot handled complex functions by only considering the real component of the data. As such, this would yield the following plot
However, newer versions consider the magnitude of the data and the zeros will only occur when both the real and imaginary components are zero. Of the two points where this is true, only one of these points is real and is able to be plotted; however, the relatively coarse sampling of ezplot isn't able to display that single point.
You could use contourc to determine the location of this point
imagesc(abs(values), 'XData', [-10 10], 'YData', [-10 10]);
axis equal
hold on
cmat = contourc(abs(values), [0 0]);
xvalues = xx(1, cmat(1,2:end));
yvalues = yy(cmat(2,2:end), 1);
plot(xvalues, yvalues, 'r*')
This is because x = y = 1 is the only solution to the given equation.
Note that the minimum value of x - log(x) is 1 and that happens when x = 1. Obviously, the same is true for y - log(y). So, -log(x)-log(y)+x+y is always greater than 2 except at x = y = 1, where it is exactly equal to 2.
As your equation has only one solution, there is no line on the plot.
To visualize this, let's plot the equation
ezplot('-log(x)-log(y)+x+y-C',[-10 10 -10 10]);
for various values of C.
% choose a set of values between 5 and 2
C = logspace(log10(5), log10(2), 20);
% plot the equation with various values of C
figure
for ic=1:length(C)
ezplot(sprintf('-log(x)-log(y)+x+y-%f', C(ic)),[0 10 0 10]);
hold on
end
title('-log(x)-log(y)+x+y-C = 0, for 5 < C < 2');
Note that the largest curve is obtained for C = 5. As the value of C is decreased, the curve also becomes smaller, until at C = 2 it completely vanishes.

Matlab Recreating freqz, normalizing x axis and getting half of plot

I have a function which is basically recreating the freqz command in matlab. I have figured out how to plot the entire transform of my frequency response, but I only need half of it, and I need to normalize it from pi to 1 (where 0:pi represents my x axis, and I want that to go to 0:1). The code is here:
function freqrespplot(b, a)
hb = fft(b,512);
ha = fft(a,512);
magh = (abs(hb) ./ abs(ha));
angh = angle(hb ./ ha);
x = linspace(0,2*pi, 512);
subplot(2,1,1);
plot(x,magh,'g');
subplot(2,1,2);
plot(x,angh,'r');
end
In the example of b = [1 2 2], a = [0 1 .8], plots like the following:
freqrespplot([1 2 2], [0 1 .8]);
Magnitude
and my corresponding phase plot is
I want the x-axis (omega) to go from 0 to 1 in both cases, and correspond to 0 to pi by taking only half of the graph, like this if possible:
You only need some small changes, marked with comments in the code below:
function freqrespplot(b, a)
hb = fft(b,512);
ha = fft(a,512);
magh = (abs(hb) ./ abs(ha));
angh = angle(hb ./ ha);
x = linspace(0,2, 513); %// 2, not 2*pi. And 513. Last value will be discarded
x = x(1:end-1); %// discard last value to avoid having 0 and 2*pi (they are the same)
subplot(2,1,1);
plot(x(1:end/2),magh(1:end/2),'g'); %// plot only half
subplot(2,1,2);
plot(x(1:end/2),angh(1:end/2),'r'); %// plot only half
end
With your example b and a this produces
You may want to include one additional sample to reach the right edge of the graph. I comment only differences with the above code:
function freqrespplot(b, a)
hb = fft(b,512);
ha = fft(a,512);
magh = (abs(hb) ./ abs(ha));
angh = angle(hb ./ ha);
x = linspace(0,2, 513);
x = x(1:end-1);
subplot(2,1,1);
plot(x(1:end/2+1),magh(1:end/2+1),'g'); %// plot only lower half plus one value
subplot(2,1,2);
plot(x(1:end/2+1),angh(1:end/2+1),'r'); %// plot only lower half plus one value
end
Compare the resulting graph (rightmost part):

plotting scatter3 and surf plots from loop in matlab

I want to plot scatter3 and surf plots from a loop. Below is my code but it isn't working...not sure where I'm going wrong but clearly something is wrong with the z matrix?
for e = 1:10;
x = rand(1,3);
y = rand(1,3);
A = x+y;
subplot(2,2,1)
p = find(A(:,1) > 1.1 & A(:,1) < 1.6);
Result = A(p,:);
scatter3(Result(:,1), Result(:,2), Result(:,3))
hold on
z(e,:) = [Result(1) Result(2) Result(3)];
end
subplot(2,2,2)
surf(z)
I will reiterate what I said in my comment to you. I got this error message when trying to run your code: Attempted to access Result(1); index out of bounds because numel(Result)=0. This is because your p condition isn't satisfied - MATLAB could not find any elements in the first column that are between 1.1 and 1.6.
As such, what I would suggest you do is check to see if Result is empty before trying to access the value itself. However, I would suggest you don't write a loop and generate all of the random values at once, then do the filtering with the Boolean conditions. Therefore, the equivalent code without using a loop would be this:
x = rand(10,3);
y = rand(10,3);
A = x+y;
p = A(:,1) > 1.1 & A(:,1) < 1.6;
z = A(p,:);
figure;
subplot(2,1,1);
scatter3(z(:,1), z(:,2), z(:,3));
subplot(2,1,2);
surf(z);
We generate 10 3D points for x and y at the beginning, then add these and store this into A. Next, we find the rows in A that are between 1.1 and 1.6 in the first column and store this as a logical array. We then use this array to index into A and store the results into z. This is the recommended approach if you want to extract certain elements into an array rather than using find.
Once we obtain z, we plot these points with scatter, then also find a surface plot with surf for the same matrix. BTW, I've fixed your subplot as you are only creating two plots, yet you are allocating space for 4 plots.
If you're absolutely bent on using your code, you would simply do this:
z = []; %// Change
for e = 1:10
x = rand(1,3);
y = rand(1,3);
A = x+y;
subplot(2,1,1)
p = find(A(:,1) > 1.1 & A(:,1) < 1.6);
Result = A(p,:);
scatter3(Result(:,1), Result(:,2), Result(:,3))
hold on
if ~isempty(Result) %// Change here
z = [z; Result(1) Result(2) Result(3)]; %// Change
end
end
subplot(2,1,2)
surf(z)
What's important is the initialization of z. I made this empty, and we only add to z if Result is not empty - this will happen if you generate a number that is not between 1.1 and 1.6.

How to plot two 1-dimensional Gaussian distributions together with the classification boundary [Matlab]?

I have two classes(normally distributed), C1 and C2, each defined by their mean and standard deviation. I want to be able to visualize the pdf plot of a normal distributions and the classification boundary between the two. Currently I have the code to plot the distributions but I'm not sure how to go about plotting the decision boundary. Any ideas would be appreciated. I have included a sample of what I want to plot. 1
Many thanks!
This is what I came up with:
% Generate some example data
mu1 = -0.5; sigma1 = 0.7; mu2 = 0.8; sigma2 = 0.5;
x = linspace(-8, 8, 500);
y1 = normpdf(x, mu1, sigma1);
y2 = normpdf(x, mu2, sigma2);
% Plot it
figure; plot(x, [y1; y2])
hold on
% Detect intersection between curves; choose threshold so you get the whole
% intersection (0.0001 should do unless your sigmas are very large)
ind = y1 .* y2 > 0.0001;
% Find the minimum values in range
minVals = min([y1(ind); y2(ind)]);
if ~isempty(minVals)
area(x(ind), minVals)
end
I don't know if this is the best way to do what you want, but it seems to work.