FunnyBuzer
FunnyBuzer

Reputation: 313

Sample t-test in Matlab

In Matlab I have to generate two Gaussian random samples with distributions:

  1. N(100,5)
  2. N(115,15)

Then run the simulation 1,000 times and compute how many times the null hypothesis was rejected out of 1,000 times for each sample sizes scanning from 2 to 50.

Finally, I need to plot the result of the rejections of H0 against the sample size.

h = zeros(1000,1);
k = 0;

for i = 1:1000
    r1 = ();
    r2 = ();
    for j= 2:50
        r1(j-1)=normrnd(100,5,[1,j]);
        r2(j-1)=normrnd(110,15,[1,j]);
    end
    h(i)=ttest2(r1,r2)
    if h(i)==1
        k=k+1;
    end
    percent_of_rejection_Null=(k/1000*100);
end
%plot(h vs sample_size)

Could somebody help me to correct the above code?

Upvotes: 1

Views: 686

Answers (1)

David
David

Reputation: 8298

There was a few issues with your code:

  1. ri is a vector of changing size so you need to append it to a struct that can store elements with different sizes -> cell array.
  2. percent_of_rejection_Null needs to be a vector to store all the values.
  3. you didn't specify what type of plot you are looking for specifically, I showed the bar plot but it's easy to adjust to the desired one you need.
  4. the calculation of h was problematic, its a vector of 50 each iteration thus need to calculate the sum of 1.

The piece of code is:

h = zeros(1000,1);
percent_of_rejection_Null = zeros(1000,1);
k = 0;

for i = 1:1000
    r1 = {};
    r2 = {};
    for j= 2:50
        r1{j-1}=normrnd(100,5,[1,j]);
        r2{j-1}=normrnd(110,15,[1,j]);
    end
    h = cellfun(@ttest2, r1, r2);
    k = sum(h==1);
    percent_of_rejection_Null(i) = (k/1000*100);
end
figure;
plot(percent_of_rejection_Null)

The resulted plot is:

enter image description here

If the output isn't what you were after, please edit your question in order for me to adjust.

Upvotes: 3

Related Questions