Why does "interp1" result in an error "the grid vectors must contain unique points"?

393 views (last 30 days)
Why does the following code return an error?
x= [1,2,3,4,1];
v= [1,1,1,1,1];
xq = [1 2 3 4 5 6 7 8 9 0 11 22 33 44 55 66 77 88 99 00 111 222 333 444 555 666 777 888 999 000];
vq = interp1(x',v',xq','linear','extrap')'
Error using griddedInterpolant
The grid vectors must contain unique points.
Error in interp1 (line 149)
F = griddedInterpolant(X,V,method);

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Jun 2019
The error happens because "interp1" requires the values of "x" to be distinct.
>> unique_x=unique(x);
returns a 1x4 vector. Meaning there are duplicate values.
I suggest using the following instead:
[~, ind] = unique(x) % ind = index of first occurrence of a repeated value
vq = interp1(x(ind)',v(ind)',xq','linear','extrap')'
This will return the indices of the unique values in "x". Then you can call "interp1" on "x" and "v" as before, but this time pass the distinct element only.
There is one unique value in "vq" as expected since all the values in "v" are the same.

More Answers (1)

Tehreem Syed
Tehreem Syed on 10 Aug 2022
Hi,
I have the same as above and I used the same function i.e. unique but it's not working. Could you please tell how to fix it?
Below is the snippet of my code.
Thanks!
  1 Comment
Steven Lord
Steven Lord on 10 Aug 2022
Looking at your Turbidity data, I suspect that two or more of the second through fifth elements of that data are identical. If two of the adjacent values are identical, for the value of i corresponding to the first of those elements will make x1 and x2 the same.
Why is this a problem? Let's look at some simpler data that has the same property I believe your Turbidity data has.
x = [1 1]; % Taking the place of Turbidity(2:3)
y = [2 3]; % Taking the place of X(2:3)
plot(x, y, 'o-')
So if I were to interpolate this y data at x = 1, what should be the interpolated value? Should it return 2, 3, or something in-between (maybe 2.5?) It's not really well-defined what the interpolated value should be, so MATLAB says something to the effect of "I'm not sure you're doing the right thing here."
z = interp1(x, y, 1)
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);
How to fix this? I'd make sure that your Turbidity data contains the correct values. If it does, think about how you want the interpolation to handle a vertical "wall" like the one in the plot above. What should the correct values be? You may need to write your own code to handle that section of your data without using interp1.

Sign in to comment.

Tags

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!