How do I plot two functions at the same time

조회 수: 6 (최근 30일)
Alyssa Cleveland
Alyssa Cleveland 2016년 2월 12일
답변: KSSV 2016년 2월 12일
Hi I am having a hard time plotting two functions at the same time and showing all the points.
This is the question I am trying to figure out.
The variance of a Bernoulli random variable is p(1 − p). Use a for loop, the var function, and your Bernoulli random variable generator to do the following: Vary p from 0 to 1 in steps of 0.05. For each value of p generate 1000 Bernoulli random variables and use the var command to compute the variance at each p value. Create figure(1) and plot your result along with the function p(1 − p) (on the same figure). Use the ’o’ marker for the points you calculated from your Bernoulli random variable generator and a black line for the curve p(1−p). Label the x-axis as ‘p’ and the y-axis as ‘variance’
This is what I have so far.
myBern=@(n,m,p)double(rand(n,m)<p)
myVar=@(p)p(1-p) plot(p,myVar(p)) n = 1; m = 1000;
for p=0:.05:1 myVar=@(p)p(1-p); x = myBern(n,m,p); disp('Variance') disp(var(x)) plot(p,var(x),'o')
end
The issues I am having are when I try to run this script for plot(p,myVar(p)) I keep getting the error "Subscript indices must either be real positive integers or logicals."
Error in @(p)p(1-p)
and in plot(p,var(x),'o') It is only plotting one point and I am not sure how to get it to plot the variance for all the points of p in the for loop.
I am also not really sure how to get the x-axis and the y-axis to stay labeled every time I run the code.
Any help or suggestions will be appreciated.

답변 (1개)

KSSV
KSSV 2016년 2월 12일
you p is taking value 0, how o can be a index? 0 cannot be a index. it Shall start with 1. You mat do the following: P = 0:0.05:1 ; Run another loop like;
for i = 1:length(p)
p = P(i) ;
end
Use this p where you want.

카테고리

Help CenterFile Exchange에서 Scatter Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by