Main Content

Regularize Irregularly Sampled Data

This example shows how to regularize irregularly sampled data to have a constant time period between measurements. You update timestamps of data read from a ThingSpeak™ channel to remove irregularity, then write the data to a channel. Timestamp variations in measured data introduced due to network latencies or hardware resets can affect data preprocessing and data analytics algorithms. Many algorithms require regularly sampled data to work correctly.

Read Data from the Weather Station Channel

ThingSpeak channel 12397 contains data from the MathWorks® weather station, located in Natick, Massachusetts. The data is collected once every minute. Field 4 of the channel contains air temperature data. To check for irregularly sampled data, read the air temperature data from channel 12397 using the thingSpeakRead function.

data = thingSpeakRead(12397,'NumMin',60,'Fields',4,'outputFormat','timetable');

Check for Irregularly Sampled Data

The data for the last 60 minutes read from channel 12397 is stored in as a timetable. Use isregular function to check if the channel data is regularly sampled. If data is irregularly sampled, generate a regularly spaced time vector for the time period of interest. Generate a new time vector using linspace with the startTime, stopTime, and the number of measurements.

regularFlag = isregular(data,'Time');

if ~regularFlag
    startTime = data.Timestamps(1);
    stopTime  = data.Timestamps(end);
    newTimeVector = linspace(startTime,stopTime,height(data)); 
    data.Timestamps = newTimeVector;

Send Data to ThingSpeak

Send the processed data to a ThingSpeak channel using the thingSpeakWrite function.

% Change the channelID and the writeAPIKey to send data to your channel.

See Also