## Detrending Data

Your Ad Here

### Introduction

The MATLAB function detrend subtracts the mean or a best-fit line (in the least-squares sense) from your data. If your data contains several data columns, MATLAB detrends each data column separately.

Removing a trend from the data enables you to focus your analysis on the fluctuations in the data about the trend. A linear trend typically indicates a systematic increase or decrease in the data. This might be caused by sensor drift, for example.

You must decide whether it makes sense to remove trend effects in the data based on the objectives of your analysis.

### Example — Removing Linear Trends from Data

This example shows how to remove a linear trend from daily closing stock prices to emphasize the price fluctuations about the overall increase. This data is available in the predict_ret_data.mat file.

You can follow along with the steps in this example to perform the following tasks:

#### Loading and Plotting Data

1. Load the sample data:

```load predict_ret_data.mat
```

This adds the variable sdata to the workspace, which contains the daily stock prices.

2. View the contents of the column vector sdata:

```sdata
```

The last data value is a NaN, which must be removed before detrending the data.

3. Identify and remove the NaN value from sdata:

`sdata(any(isnan(sdata),2),:) = []`

For more information about removing NaNs, see Removing NaNs from the Data.

4. Plot the data:

```plot(t, sdata,'+')
legend('Original Data',1);
xlabel('Time (days)');
ylabel('Stock Price (dollars)');```

Daily Closing Stock Prices

Notice the systematic increase in the stock prices when this data was collected.

#### Detrending Data and Plotting Results

1. Remove a best-fit line (in the least-squares sense) from sdata and save the results to a new variable, detrend_sdata:

`detrend_sdata=detrend(sdata);`
2. Plot the detrended data in a new MATLAB Figure window:

```figure
plot(detrend_sdata,'-')
legend('Detrended Data',2)
xlabel('Time (days)');
ylabel('Detrended Stock Price (dollars)');```

Stock Prices with the Removed Linear Trend

Notice that the data is now centered about 0 and the linear drift is removed from the data.

© 1984-2007 The MathWorks, Inc. Terms of Use Patents Trademarks Acknowledgments

Your Ad Here