Darqer
Darqer

Reputation: 2887

How to calculate p-value for t-test in MATLAB?

Is there some simple way of calculating of p-value of t-Test in MATLAB.

I found something like it however I think that it does not return correct values:

Pval=2*(1-tcdf(abs(t),n-2))

I want to calculate the p-value for the test that the slope of regression is equal to 0. Therefore I calculate the Standard Error

$SE= \sqrt{\frac{\sum_{s = i-w }^{i+w}{(y_{s}-\widehat{y}s})^2}{(w-2)\sum{s=i-w}^{i+w}{(x_{s}-\bar{x}})^2}}$

where $y_s$ is the value of analyzed parameter in time period $s$,
$\widehat{y}_s$ is the estimated value of the analyzed parameter in time period $s$,
$x_i$ is the time point of the observed value of the analysed parameter,
$\bar{x}$ is the mean of time points from analysed period and then
$t_{score} = (a - a_{0})/SE$ where $a_{0}$ where $a_{0} = 0$.

Upvotes: 1

Views: 25878

Answers (1)

Zana
Zana

Reputation: 41

I checked that p values from ttest function and the one calculated using this formula:

% Let n be your sample size
% Let v be your degrees of freedom

% Then:
pvalues = 2*(1-tcdf(abs(t),n-v)) 

and they are the same!

Example with Matlab demo dataset:

load accidents
x = hwydata(:,2:3);
y = hwydata(:,4);
stats = regstats(y,x,eye(size(x,2)));
fprintf('T stat using built-in function: \t %.4f\n', stats.tstat.t);
fprintf('P value using built-in function: \t %.4f\n', stats.tstat.pval);
fprintf('\n\n');

n = size(x,1);
v = size(x,2);
b = x\y;
se = diag(sqrt(sumsqr(y-x*b)/(n-v)*inv(x'*x)));
t = b./se;
p = 2*(1-tcdf(abs(t),n-v));
fprintf('T stat using own calculation: \t\t %.4f\n', t);
fprintf('P value using own calculation: \t\t %.4f\n', p);

Upvotes: 4

Related Questions