Linear interpolation using inter1 function in matlab

9 views (last 30 days)
I have data in this format. I am reading the data using readtable command.
2 6
3 8
4 9
5 0
I am using this code to perform linear interpolation in matlab. Data is read using following command X_t = readtable()
for i = 1:height(X_t)-1
x1(i) = X_t.T(i);
x2(i) = X_t.T(i+1);
y1(i) = X_t.G(i);
y2(i) = X_t.G(i+1);
for j = X_t.T(i) : X_t.T(i+1) -1
y_inter = interp1([x1,x2],[y1,y2]);
I am not sure if I am doing this correctly or not. Please help me.

Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 5 Aug 2022
Edited: Bjorn Gustavsson on 5 Aug 2022
First you should learn to read the help to the function you struggle with. Do that carefully and you will see that the typical use of interp1 is:
Yi = interp1(x,y,xi);
Where you send in a third input argument for the points along the x-direction that you want the interpolated values Yi at. You have to change your call to something like:
x = X_t.T;
y = X_t.G;
Xi = linspace(min(x),max(x),10*numel(x)); % this you might want to modify to get values at your points-of-interest
y_inter = interp1(x,y,Xi);
Steven Lord
Steven Lord on 5 Aug 2022
That means two or more of your X values are the same. MATLAB can't interpolate the data in that case. Consider a simple example:
X = [0 0.5 0.5 1];
Y = [0 0 1 1];
plot(X, Y, 'o-')
If I were to interpolate this data to try to find the value of Y at X = 0.5, what should that value be? Should it be 0, 1, or a value somewhere inbetween? Since that question is ambiguous, MATLAB throws an error.
interp1(X, Y, 0.5) % Error
Error using matlab.internal.math.interp1
Sample points must be unique.

Error in interp1 (line 188)
VqLite = matlab.internal.math.interp1(X,V,method,method,Xqcol);

Sign in to comment.


Find more on Interpolation in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!