Lina
Lina

Reputation: 451

empirical mean and variance plot in matlab with the normal distribution

I'am new in matlab programming,I should Write a script to generate a random sequence (x1,..., XN) of size N following the normal distribution N (0, 1) and calculate the empirical mean mN and variance σN^2 Then,I should plot them:

this is my essai:

function f = normal_distribution(n) 
x =randn(n); 
muem = 1./n .* (sum(x)); 
muem
%mean(muem)
vaem = 1./n .* (sum((x).^2));
vaem
hold on
plot(x,muem,'-') 
grid on 
plot(x,vaem,'*') 

NB:those are the formules that I have used:

enter image description here

I have obtained,a Figure and I don't know if is it correct or not ,thanks for Help

Upvotes: 0

Views: 2010

Answers (1)

Fijoy Vadakkumpadan
Fijoy Vadakkumpadan

Reputation: 668

From your question, it seems what you want to do is calculate the mean and variance from a sample of size N (nor an NxN matrix) drawn from a standard normal distribution. So you may want to use randn(n, 1), instead of randn(n). Also as @ThP pointed out, it does not make sense to plot mean and variance vs. x. What you could do is to calculate means and variances for inceasing sample sizes n1, n2, ..., nm, and then plot sample size vs. mean or variance, to see them converge to 0 and 1. See the code below:

function [] = plotMnV(nIter) 
means = zeros(nIter, 1);
vars = zeros(nIter, 1);
for pow = 1:nIter
     n = 2^pow;
     x =randn(n, 1); 
     means(pow) = 1./n * sum(x); 
     vars(pow) = 1./n * sum(x.^2);
end

plot(1:nIter, means, 'o-');
hold on;
plot(1:nIter, vars, '*-');

end

For example, plotMnV(20) gave me the plot below.

enter image description here

Upvotes: 2

Related Questions