I am trying to get a graph made for my interpolation program (basically it takes a test function and creates lines utilizing an interpolation method)

clear all;
close all; 

x1= [-1 0.75 -0.5 -0.25 0 0.25 0.5 0.75 1];

title('Figure 777')
for loop=1:1:6

    hold on
    hold on
[p1,s1,u1] = polyfit(x1,y1,4);
Y1=polyval(p1, x2, s1, u1);
subplot (6,2,1)

[p2, s2, u2] = polyfit(x1,y1,8);
Y2 = polyval(p2, x2, s2, u2);
plot(x2,Y2, 'b', 'linewidth', 6);

Y3 = interp1(x1, y1, x2, 'linear');
plot(x2, Y3, 'b', 'linewidth', 6);

Y4 = interp1(x1,y1,x2, 'nearest');
plot(x2, Y4, 'b', 'linewidth', 6);

Y5 = interp1(x1,y1,x2, 'spline');
plot(x2, Y5, 'b', 'linewidth', 6);

%%%(F)%%%(This method does not exist for Matlab R2017a)
Y6 = interp1(x1,y1,x2, 'makima');
plot(x2, Y6, 'b', 'linewidth', 6);

However, none of the lines appear when I run the program. Only the dots. Furthermore I receive these errors:

Warning: Polynomial is badly conditioned. Add points with distinct X values or reduce the degree of the polynomial. In polyfit (line 73) In HwSixTwo (line 27)

Error using griddedInterpolant The grid vectors must contain unique points.

Error in interp1 (line 149) F = griddedInterpolant(X,V,method);

Error in HwSixTwo (line 33) Y3 = interp1(x1, y1, x2, 'linear');

  • 1
    Did you look at the contents of x2? Does it match your expectation? I bet it doesn't. Also note that you are missing a minus sign in x1, which is what causes the error (the x values must be monotonic for interp1). – Cris Luengo Apr 16 at 3:50

Well one bug that would certainly not generate intended results is here:


I'm assuming it's your intent to create 1001 points evenly spaced between -1 to 1. This code is not doing this. The middle number specifies what the spacing is in between successive numbers. 1001 does not make sense which generates only one value which is -1.

Replace your code with the linspace function:

x2 = linspace(-1, 1, 1001);

Also, you're missing a minus sign in one of your values in x1 - the 0.75:

x1= [-1 -0.75 -0.5 -0.25 0 0.25 0.5 0.75 1];
    %    ^^^

As Cris noted, your x values must be monotonic or increasing / decreasing in one direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.