Fit an Autoregression Model to the Tidal Depth Data

This example shows how to fit an autoregression (AR) model for data in your ThingSpeak™ channel and calculate the regression parameters along with their uncertainties. Autoregression models are used to represent a time-dependent process in nature.

Read Data from the Ockway Bay Real-Time Tide Gauge

ThingSpeak channel 50289 contains data about tidal depth at Ockway Bay. The data is collected once every 5 minutes. Field 1 of the channel contains tidal depth data.

% Read the data using the |thingSpeakRead| function from channel 50289 on a particular day, for example, July 01, 2016.
startDate = datetime('July 1, 2016 12:01:00 AM');
endDate = datetime('July 2, 2016 12:01:00 AM');
dateRange = startDate:endDate;

Fit an AR Model to the Data

Use the iddata function to create an iddata object of the tidal depth data. Use detrend to ensure the data has a zero mean.

sampleTime = 5;
IDdata = iddata(data,[],sampleTime,'OutputName',{'Tidal Depth'},'TimeUnit','minutes')
IDdata = detrend(IDdata,0);
IDdata =

Time domain data set with 288 samples.
Sample time: 5 minutes

Outputs           Unit (if specified)
Tidal Depth

Fit Model to Data

Since the tidal depth varies with time, use the ar function to fit a discrete-time autoregressive model to the data.

modelOrder = 8;
sys = ar(IDdata,modelOrder)
sys =
Discrete-time AR model: A(z)y(t) = e(t)

A(z) = 1 - 1.154 z^-1 - 0.1668 z^-2 + 0.2144 z^-3 + 0.2974 z^-4
- 0.4227 z^-5 + 0.1509 z^-6 - 0.1612 z^-7 + 0.2491 z^-8

Sample time: 5 minutes

Parameterization:
Polynomial orders:   na=8
Number of free coefficients: 8
Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.

Status:
Estimated using AR ('fb/now') on time domain data "IDdata".
Fit to estimation data: 98.5%
FPE: 0.04741, MSE: 0.04485

Show Parameters

Use the getpvec function to show the estimated parameters along with their uncertainties.

[Parameters,Uncertainties] = getpvec(sys)
Parameters =

-1.1543
-0.1668
0.2144
0.2974
-0.4227
0.1509
-0.1612
0.2491

Uncertainties =

0.0580
0.0918
0.0932
0.0918
0.0921
0.0970
0.0962
0.0647

The output shows the estimated AR model parameters and the one standard deviation value of the estimated parameters.

Write Parameters to ThingSpeak

Use the thingSpeakWrite function to write the array of values to ThingSpeak, with one vaue per field. Transpose the data to be 8 x 1. Change the channelID and the writeAPIKey to send data to your channel.

channelID=17504;
writeAPIKey='23ZLGOBBU9TWHG2H';
response = thingSpeakWrite(channelID,'Values',Parameters','WriteKey',writeAPIKey)
response =

struct with fields:

Field1: '-1.154266029802091'
Field2: '-0.1668388400729965'
Field3: '0.2143807521019717'
Field4: '0.2973816840220466'
Field5: '-0.4226981725238166'
Field6: '0.1509427726183032'
Field7: '-0.1612303290788889'
Field8: '0.2490548535561231'
Latitude: []
Longitude: []
ChannelID: 17504
Created: 10-Jan-2019 15:10:41
LastEntryID: 20736
Altitude: []