Why is my code not working? I'm supposed to determine the mean of a biased and unbiased sample variance and plot but it's not working

4 views (last 30 days)
%% 1. Sample variance bias
Nd1 = [5, 10, 50, 100, 500, 1000];
trials2 = 100;
sigma = 4;
samplevar = zeros(length(Nd1),trials2);
samplevarbias = zeros(length(Nd1),trials2);
for i=1:length(Nd1)
uncorrected = (1/Nd1)*(sum(4^2 * 0^2));
corrected = (1/Nd1 - 1)*(sum((4-0)^2));
end
% Compute mean of the two estimators.
% You may use matlab's mean function to compute the mean, but be careful to
% specify which dimension of the matrices you want to compute the mean
% over!
meansvar = mean(corrected); % enter code
meansvarbias = mean(uncorrected); % enter code
% Plot figure. You do not need to modify this section.
figure; plot(Nd1,meansvar-sigma^2,'bo-','LineWidth',5)
hold on; plot(Nd1,meansvarbias-sigma^2,'rs-','LineWidth',5)
xlabel('$N_D$','Interpreter','latex','fontsize',20)
ylabel('Bias','Interpreter','latex','fontsize',20)
title('Bias of variance estimators','Interpreter','latex','fontsize',20)

Answers (1)

Image Analyst
Image Analyst on 4 Oct 2022
I think you need an inner loop with Nd iterations. Here, start with this (still broken) code and see if you can figure it out:
%% 1. Sample variance bias
Nd1 = [5, 10, 50, 100, 500, 1000];
trials2 = 100;
sigma = 4;
samplevar = zeros(length(Nd1),trials2);
samplevarbias = zeros(length(Nd1),trials2);
for i=1:length(Nd1)
thisN = Nd1(i);
fprintf('Running with i = %d. Will now do %d iterations.\n', thisN, thisN);
% So the simulation with this number of iterations.
for k = 1 : thisN
uncorrected = (1/thisN)*(sum(4^2 * 0^2)); % Not sure about these!
corrected = (1/thisN - 1)*(sum((4-0)^2));
end
end
% Compute mean of the two estimators.
% You may use matlab's mean function to compute the mean, but be careful to
% specify which dimension of the matrices you want to compute the mean
% over!
meansvar = mean(corrected); % enter code
meansvarbias = mean(uncorrected); % enter code
% Plot figure. You do not need to modify this section.
figure; plot(Nd1,meansvar-sigma^2,'bo-','LineWidth',5)
hold on; plot(Nd1,meansvarbias-sigma^2,'rs-','LineWidth',5)
xlabel('$N_D$','Interpreter','latex','fontsize',20)
ylabel('Bias','Interpreter','latex','fontsize',20)
title('Bias of variance estimators','Interpreter','latex','fontsize',20)
fprintf('Done!\n')

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by