Fixes x data so that interp1 doesn't return error:
'The values of X should be distinct.'
Checks for duplicate values in input 1D data array and returns array where all values are distinct. If duplicates are found, values are separate by small value (eps).
useage:
x = nonduplicate(x);
yi = interp1(nonduplicate(x),y,xi)
Example:
interp1([1,1,2],[1,1,2],1.5)
returns an error.
interp1(nonduplicate([1,1,2]),[1,1,2],1.5)
works just fine.
Orlando - unique returns a smaller array, [1,1,2] becomes [1,2]. While nonduplicate keeps the same number of values, but slightly shifts them so [1,1,2] becomes [1,1+eps,2]. The idea was to get interp1 to work by changing the values as little as possible.
'Anon' - Great point, this code is not a good idea if there is a lot of noise or large outliers in the y data. I hadn't heard of consolidator - I will check it out.
You implicitly assume that the last of a subsequent number of repetitions in the x vector is the "valid" one. But do you think this assumption is always justified?
x = [1,1,1,2];
y = [1,5,1,2];
xi = 1.5;
yi = interp1(nonduplicate(x),y,1.5)
yi =
1.500000000000000
Duplicate values in x may arise from multiple measurements at the same location (in time or in space or elsewhere). As such, the above could also look like this:
x = [1,1,1,2];
y = [1,1,5,2];
xi = 1.5;
yi = interp1(nonduplicate(x),y,1.5)
yi =
3.500000000000001
In such case, wouldn't it be better to e.g. take the mean of y values for repeated values in x? There might be cases where your strategy might be a reasonable way to address this problem, but in general, I'd strongly recommend to use consolidator available on the FEX.