4
votes

I'm having a problem with interpolation from a non-monotonic function.

x=[34,35,36,37,38,39,41,42,43,44,45,46]
y=[0.33 0.166 0.25 0.33 0.5 0.58 0.66 0.66 0.5 0.58 0.8 0.66]

I want to be able to interpolate the X value that corresponds to a Y value of 0.25.

When plotting (x,y) I can see that there are two points that corresponds to a Y value of 0.25, so normal interpolation (using interp1) would not work.

Error: "The grid vectors are not strictly monotonic increasing."

Is there a way to interpolate both points and then calculate their mean, I couldn't find anything that fits my problem.

3
where are the two values that correspond to the same 0.25 value i only see one 0.25 value in the y vector?Nikos M.
Indeed, but there is also another "hidden" value of 0.25 between the first (0.33) and second (0.166) points which I also want to interpolate.G.N.
then use a non-linear interpolation scheme as this will yield the correct result and not a linear interpolation methodNikos M.

3 Answers

3
votes

You can first compute the mean of the douplicates and then interpolate:

%test data
x=[34,35,36,37,38,39,41,42,43,44,45,46];
y=[0.33 0.166 0.25 0.33 0.5 0.58 0.66 0.66 0.5 0.58 0.8 0.66];

% sort values
[~,idx] = sort(y);
x = x(idx);
y = y(idx);

% use all values only once. Average the values
y_unique = unique(y);
x_unique = zeros(size(y_unique));
for i = 1:length(y_unique)
   x_unique(i) =  mean(x(y==y_unique(i)));
end

% test
interp1(y_unique,x_unique,0.33)
2
votes

Iterate through your array and detect if your query value is passed. Then take the average value.

%test data
x=[34,35,36,37,38,39,41,42,43,44,45,46];
y=[0.33 0.166 0.25 0.33 0.5 0.58 0.66 0.66 0.5 0.58 0.8 0.66];

%value to query
yq = 0.25;
result = [];
for i = 1:length(y)-1
    if (y(i) <= yq && yq < y(i+1)) || (y(i) > yq && yq >= y(i+1))
        result(end+1) = interp1([y(i),y(i+1)],[x(i),x(i+1)],yq);
    end
end

xq = mean(result);
0
votes

You can select the unique points as:

% x and y are your data available
[xN, index] = unique(x);
yN = y(index);

% Now you have only unique x and y values stored in xN and yN

Note, that this will discard your duplicate data points.