Search code examples
matlabhistogramnormalizationnormal-distributionbest-fit-curve

MATLAB error: Vectors must be the same length


Hi I am trying to overlay histogram with normal distribution curve and I get an error: Vectors must be the same length.

Can anybody explain what mistake I am doing here?

This is the code I use:

X = normrnd(1.5,.1,1,1000)
[hy, hx] = hist(X,50);
hy = hy/numel(X)/(hx(2)-hx(1)); 
bar(hx,hy), colormap(bone);

z=-4:0.1:4;
pdf=(1/(std(X)*sqrt(2*pi)))*exp(-0.5*((X - mean(X))/std(X)).^2);
hold on, plot(z,pdf,'LineWidth',1,'Color','red');

Solution

  • In this code the problem is related to the fact that: vector pdf has length = 1000, while vector z has length = 81. They should have the same length in order to correspond at the axis x and y respectively.

    Here the solution:

    X = normrnd(1.5,.1,1,1000);
    [hy, hx] = hist(X,50);
    hy = hy/numel(X)/(hx(2)-hx(1)); 
    
    figure
    bar(hx,hy);
    colormap(bone);
    
    z=-4:0.1:4;
    pdf=(1/(std(X)*sqrt(2*pi)))*exp(-0.5*((z - mean(X))/std(X)).^2);
    hold on;
    plot(z,pdf,'LineWidth',1,'Color','red');
    

    enter image description here