function p = chitest(x,k) % MS-E2170 Simulation % Exercise 1.4: Chi-square test (Demo) % function p = chitest(x,k) % This function returns the p-value of the chi-square test % % --------------------------------------------------------------- % INPUT % x: Observations (Nx1 double) % k: Number of sub intervals (1x1 double) % --------------------------------------------------------------- % OUTPUT % p: p-value of the chi-square test (1x1 double) % --------------------------------------------------------------- % Created: % 2018-02-19 Heikki Puustinen % First calculate the sample size. N = length(x); % The sub intervals of [0 1] are [(i-1)/k, i/k], i = 1,2,...,k. % To calculate the observed values within each sub interval: % Initialize the variable where the number of occurrences are stored. f = zeros(k,1); % Loop through sub intervals. for ii = 1:k % Count how many xs are within the ii:th sub interval. f(ii) = sum(x > (ii-1)/k & x <= (ii/k)); end % The test statistics: X2 = sum((f - N/k).^2 ./ (N/k)); % The P-value of the test is the tail probability of the chi-square % distribution at X2: p = 1 - x2cdf(X2,k-1);