我试图创建(在r中)等效于下面的MATLAB函数,它将从N(m1,(s1)^ 2)和N(m2,(s2)^ 2)的混合中生成n个样本, ,alpha,来自第一个高斯。
我有一个开始,但是结果在MATLAB和R之间明显不同(即,MATLAB结果偶尔给出+ -8的值,但R版本甚至从未给出+ -5的值)。请帮我理清这里有什么问题。谢谢 :-)
例如:
绘制来自N(0,1)和N(0,36)混合的1000个样本与来自第一高斯的95%样本。将样本标准化为平均值零和标准偏差一。
MATLAB
功能
function y = gaussmix(n,m1,m2,s1,s2,alpha)
y = zeros(n,1);
U = rand(n,1);
I = (U < alpha)
y = I.*(randn(n,1)*s1+m1) + (1-I).*(randn(n,1)*s2 + m2);履行
P = gaussmix(1000,0,0,1,6,.95)
P = (P-mean(P))/std(P)
plot(P)
axis([0 1000 -15 15])
hist(P)
axis([-15 15 0 1000])导致情节
产生的hist
[R
yn
s
sn
plot(sn, xlim=range(0,1000), ylim=range(-15,15))
hist(sn, xlim=range(-15,15), ylim=range(0,1000))导致情节
产生的hist
一如既往,谢谢!
解
gaussmix
U
I
y
(1-I)*rnorm(nsim,mean=mean_2,sd=std_2)
return(y)
}
z1
z1_standardized
z2
z2_standardized
z3
z3_standardized
par(mfrow=c(2,3))
hist(z1_standardized,xlim=c(-10,10),ylim=c(0,500),
main="Histogram of 95% of N(0,1) and 5% of N(0,36)",
col="blue",xlab=" ")
hist(z2_standardized,xlim=c(-10,10),ylim=c(0,500),
main="Histogram of 80% of N(0,1) and 10% of N(3,1)",
col="blue",xlab=" ")
hist(z3_standardized,xlim=c(-10,10),ylim=c(0,500),
main="Histogram of samples of LN(0,1)",col="blue",xlab=" ")
##
plot(z1_standardized,type='l',
main="1000 samples from a mixture N(0,1) and N(0,36)",
col="blue",xlab="Samples",ylab="Mean",ylim=c(-10,10))
plot(z2_standardized,type='l',
main="1000 samples from a mixture N(0,1) and N(3,1)",
col="blue",xlab="Samples",ylab="Mean",ylim=c(-10,10))
plot(z3_standardized,type='l',
main="1000 samples from LN(0,1)",
col="blue",xlab="Samples",ylab="Mean",ylim=c(-10,10))