0

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');
rebatoma
  • 734
  • 1
  • 17
  • 32
Michal
  • 215
  • 3
  • 11
  • Check using the debugger the size of the vectors – rebatoma Oct 18 '15 at 21:42
  • all algebraic operation look ok . The error seems to be related to the last line, but I don't understand this – Michal Oct 18 '15 at 21:52
  • The lengths of z and pdf are the same? – rebatoma Oct 18 '15 at 21:59
  • 1
    I checked, the error is due to the fact that `z` and `pdf` doesn't have the same length. I think also this is due to the error in the computation of `pdf`, in particular, you can compute a pdf using the random term `X`. I think the right computation should be something like this: `pdf=(1/(std(X)*sqrt(2*pi)))*exp(-0.5*((z - mean(X))/std(X)).^2);` – rebatoma Oct 18 '15 at 22:13

1 Answers1

1

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

rebatoma
  • 734
  • 1
  • 17
  • 32
  • I am not sure if this the right way, the area under the curve doesn't integrate to 1. (I guess for a better picture z can be run for z=min(X):0.01:max(X);) – Michal Oct 18 '15 at 22:54
  • can this be presented this way? X = normrnd(1.5,.1,1,1000); [hy, hx] = hist(X,50); hy = hy/numel(X)/(hx(2)-hx(1)); bar(hx,hy/sum(hy)), colormap(bone); %bar(hx,hy), colormap(bone); %bar(hx,hy/trapz(hx,hy)), colormap(bone); z=min(X):0.01:max(X); %z=-4:0.01:4; pdf=(1/(std(X)*sqrt(2*pi)))*exp(-0.5*((z - mean(X))/std(X)).^2); pdf=pdf/sum(pdf) hold on, plot(z,pdf,'LineWidth',1,'Color','red'); – Michal Oct 18 '15 at 23:04
  • @Michal I don't know if this last solution proposed by you is right one. But this is not a question for stack-overflow. Maybe you can post this specific question in other communities (i.e., Mathematics or Mathematic) – rebatoma Oct 19 '15 at 07:06