histogram plotting issue

2 views (last 30 days)
raymond
raymond on 23 Nov 2011
can someone please help me figure out a issue im having plotting the results of a simulation i ran. what im trying to do is use a histogram to plot my data but when i try that i get no results on screen and the axis are all wrong however when i use use plot i get the points on screen altough barely visible without a line connecting them can someone please tell me how to fix my histogram problem or tell me how to get a line to fit my data points when i use plot
here's a plot and hist version of my code
%plot version
win=0
step=0
for p=.1:.1:.9
for i=1:1:100
a=3
b=3
c=3
while a>0 && b>0 && c>0
step=step+1
d=rand(1,3)
if d(1,1)<p && d(1,2)<p && d(1,3) <p
a=a+0
b=b+0
c=c+0
elseif d(1,1)>p && d(1,2) >p &&d(1,3) >p
a=a+0
b=b+0
c=c+0
elseif d(1,1)<p && d(1,3) < p
a= a -1
b= b+2
c= c-1
elseif d(1,1)>p &&d(1,3) >p
a= a -1
b= b+2
c= c-1
elseif d(1,3)<p &&d(1,2) < p
a= a +2
b= b-1
c= c-1
elseif d(1,2)>p && d(1,3) >p
a= a +2
b= b-1
c= c-1
elseif d(1,1)<p &&d(1,2) < p
a= a -1
b= b-1
c= c+2
elseif d(1,1)>p && d(1,2) >p
a= a -1
b= b-1
c= c+2
end
end
win=win+1
end
%axis([0 5 0 75 ])
avg=step/100
plot(p,avg)
hold on
end
disp avg
%histogram version
win=0
step=0
for p=.1:.1:.9
for i=1:1:100
a=3
b=3
c=3
while a>0 && b>0 && c>0
step=step+1
d=rand(1,3)
if d(1,1)<p && d(1,2)<p && d(1,3) <p
a=a+0
b=b+0
c=c+0
elseif d(1,1)>p && d(1,2) >p &&d(1,3) >p
a=a+0
b=b+0
c=c+0
elseif d(1,1)<p && d(1,3) < p
a= a -1
b= b+2
c= c-1
elseif d(1,1)>p &&d(1,3) >p
a= a -1
b= b+2
c= c-1
elseif d(1,3)<p &&d(1,2) < p
a= a +2
b= b-1
c= c-1
elseif d(1,2)>p && d(1,3) >p
a= a +2
b= b-1
c= c-1
elseif d(1,1)<p &&d(1,2) < p
a= a -1
b= b-1
c= c+2
elseif d(1,1)>p && d(1,2) >p
a= a -1
b= b-1
c= c+2
end
end
win=win+1
end
%axis([0 5 0 75 ])
avg=step/100
hist(avg,p)
hold on
end
disp avg

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 23 Nov 2011
You need to learn to use vector or matrix, the essence of MATLAB.
Pre-allocate you p as p=.1:.1:.9; p will be a 1x9 vector, you can reference individual element as p(1), p(2), etc.
Pre-allocate avg=zeros(size(p)), avg will be a all-zero vector the same size as p. Go through your loop, calculate the value of avg that is corresponding to p.
Then you can use plot(p,avg). It will plot a curve.
Right now, you are plotting one dot at a time. Since you have the hold on, it shows all the dots.
Add a semi-colon ";" at the end of each line, it will prevent the echo in the MATLAB Command Window, which slows down the program quite a lot.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!