Search code examples
matlabinterpolation

Linear Interpolation in MATLAB


I have two arrays the first one represents the time axis with time stamp 1 min

time=[0,60,60,120,180,240,300,360,420,480,540]

and the second array represents a data values as follows

data=[18,12,12,0,7,9,6,8,12,18,0]

what im trying to do is two things:

1-I would like to fix the time axis to have 1 second time stamp

2-Perform linear Interpolation as follows:

for example i have

enter image description here

and i would like to have sth like this:

enter image description here

In case of time repetation like the repated 60 seconds the duplication should be deleted


Solution

  • You can remove duplicates (the first value is kept) with

    time = [0,60,60,120,180,240,300,360,420,480,540];
    data = [18,12,12,0,7,9,6,8,12,18,0];
    [time_u unique_indeces] = unique(time);
    data_u = data(unique_indeces);
    clear unique_indeces;
    

    and interpolate with

    time_i = linspace(min(time), max(time), max(time) - min(time) + 1);
    data_i = interp1(time_u, data_u, time_i);
    

    I prefer linspace because I usually want to set the number of data points and not the space between points but you can also use min(time):max(time) or time(1):time(end) instead.

    This code will also sort your data points by time.