# dwtest

Class: LinearModel

Durbin-Watson test of linear model

## Syntax

```P = dwtest(mdl)[P,DW] = dwtest(mdl)[P,DW] = dwtest(mdl,method)[P,DW] = dwtest(mdl,method,tail)```

## Description

`P = dwtest(mdl)` returns the p-value of the Durbin-Watson test on the `mdl` linear model.

```[P,DW] = dwtest(mdl)``` returns the Durbin-Watson statistic.

```[P,DW] = dwtest(mdl,method)``` specifies the method `dwtest` uses to compute the p-value.

```[P,DW] = dwtest(mdl,method,tail)``` specifies the alternative hypothesis.

## Input Arguments

`mdl`

Linear model, as constructed by `fitlm` or `stepwiselm`.

`method`

Algorithm for computing the p-value:

• `'exact'` — Calculates an exact p-value using Pan's algorithm.

• `'approximate'` — Calculates the p-value using a normal approximation.

Default: `'exact'` when the sample size is less than `400`, `'approximate'` otherwise

`tail`

`dwtest` tests whether `mdl` has no serial correlation against one of these alternative hypotheses:

TailAlternative Hypothesis
`'both'`

Serial correlation is not 0.

`'right'`

Serial correlation is greater than 0 (right-tailed test).

`'left'`

Serial correlation is less than 0 (left-tailed test).

Default: `'both'`

## Output Arguments

 `P` p-value of the test, a scalar. `dwtest` tests if the residuals are uncorrelated, against the alternative that there is autocorrelation among them. Small values of `P` indicate that the residuals are correlated. `DW` Value of the Durbin-Watson statistic, a scalar.

## Definitions

### Durbin-Watson Statistic

Let r be the vector of residuals (in `mdl.residuals.response`). The Durbin-Watson statistic is

$DW=\frac{\sum _{i=1}^{n-1}{\left({r}_{i+1}-{r}_{i}\right)}^{2}}{\sum _{i=1}^{n}{r}_{i}^{2}}.$

## Examples

expand all

### Test Residuals for Autocorrelation

Examine whether the residuals from a fitted model of census data over time have autocorrelated residuals.

Load the census data and create a linear model.

```load census mdl = fitlm(cdate,pop);```

Find the p-value of the Durbin-Watson autocorrelation test.

`P = dwtest(mdl)`
```P = 0```

There is significant autocorrelation in the residuals.

## Algorithms

Approximate calculation of the p-value uses a normal approximation [1]. Exact calculation uses Pan's algorithm [2].

## References

[1] Durbin, J., and G. S. Watson. Testing for Serial Correlation in Least Squares Regression I. Biometrika 37, pp. 409–428, 1950.

[2] Farebrother, R. W. Pan's Procedure for the Tail Probabilities of the Durbin-Watson Statistic. Applied Statistics 29, pp. 224–227, 1980.