Two-Sample Kolmogorov-Smirnov Test Statistic
8 views (last 30 days)
Show older comments
Hi,
Matlab kstest2 function computes the Kolmogorov-Smirnov Test Statistic as:
D* = max x (|F1(x) - F2(x)|)
where F1(x) is the proportion of x1 values less than or equal to x and F2(x) is the proportion of x2 values less than or equal to x.
However, I need to compute the Kolmogorov-Smirnov Test Statistic as:
D* = ( (n1*n2) / (n1+n2) )^(1/2) * max x (| (1/n1)*F1(x) - (1/n2)*F2(x) |)
where n1 and n2 are x1 and x2 samples sizes, respectively.
Could you please help me with the code to do this?
Thanks in advance!
0 Comments
Answers (1)
Aditya
on 3 Mar 2025
Hi Barbara ,
In order to compute the Kolmogorov-Smirnov test statistic as you've described, you can use the following MATLAB code. This code calculates the statistic using your specified formula:
function D_star = custom_kstest2(x1, x2)
% Sort the samples
x1 = sort(x1);
x2 = sort(x2);
% Sample sizes
n1 = length(x1);
n2 = length(x2);
% Combined sample
combined_sample = unique([x1; x2]);
% Initialize the empirical distribution functions
F1 = zeros(size(combined_sample));
F2 = zeros(size(combined_sample));
% Calculate the empirical distribution functions
for i = 1:length(combined_sample)
F1(i) = sum(x1 <= combined_sample(i)) / n1;
F2(i) = sum(x2 <= combined_sample(i)) / n2;
end
% Calculate the maximum difference
max_diff = max(abs(F1 - F2));
% Calculate the modified Kolmogorov-Smirnov statistic
D_star = sqrt((n1 * n2) / (n1 + n2)) * max_diff;
end
% Example usage:
x1 = [1, 2, 3, 4, 5];
x2 = [2, 3, 4, 5, 6];
D_star = custom_kstest2(x1, x2);
disp(D_star);
Hope, this helps.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!