A problem drawing a graph in matlab

2 views (last 30 days)
googo
googo on 27 Mar 2013
I'm trying to draw a graph of density in matlab and I'm encountering several problems.
First, binValues is a function that does this :
(for example:)
binValues([24767 33119 30397 31150 26729 29446 28574 29085]',4)
ans =
24767 26855 2
26855 28943 1
28943 31031 3
31031 33119 2
here n = 4, number of categories. In the code at the bootom n=3.
This is the code that doesn't work well:
function graph = histogram(z,n)
data = binValues(z,n); %
z=sort(z);
sum=0;
for i=1:n
sum=sum+data(i,3);
end
density = zeros(n,1);
for i=1:n
density(i)=(data(i,3))/(sum);
end
dens=zeros(1,length(z));
for j=1:length(z)
for i=1:n
if (z(j)>data(i,1)) && (z(j)<=data(i,2))
dens(j)=density(i);
end
end
end
y = zeros(1,2*length(z));
xnew = zeros(1,2*length(z));
xnew(1) = z(1);
xnew(2) = z(1);
y(1) = 0;
y(2) = dens(1);
for i=2:length(z)
xnew(2*i-1) = z(i);
xnew(2*i) = z(i);
y(2*i-1) = dens(i-1);
y(2*i) = dens(i);
end
graph = plot(xnew,y);
end
When I run it for histogram([1 2 2 1 1 1 3 3 2 2 2 1 1 1 4]',3), the plot seems to be biased to the right. It suupose to be like the one on the left, see here : http://oi48.tinypic.com/os4j7d.jpg
Any ides what's the problem? I'm not allowed in this exercise to use other functions besides plot,xlim,ylim,min and max.
Thank's!
  1 Comment
googo
googo on 27 Mar 2013
Any problem with the question? I truly need your help. Thank you very much.

Sign in to comment.

Answers (1)

Doug Hull
Doug Hull on 27 Mar 2013
Why not use the built in hist command in MATLAB to get a histogram?
  1 Comment
googo
googo on 27 Mar 2013
Edited: googo on 27 Mar 2013
I'm not allowed to use this. Looking at the code and the result i'm not far away but something is definitely wrong. ======================================================= ok... I think I fix it... it was suppose to be *if (z(j)>=data(i,1)) && (z(j)<data(i,2))*
Any ideas how to normalize this histogram, so it will be a probability density function? And how do i find what is the surface under the graph?

Sign in to comment.

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!