-1

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; 
clc;

x1= [-1 0.75 -0.5 -0.25 0 0.25 0.5 0.75 1];
x2=-1:1001:1;

y1=1./(1+25.*x1.^2);
y2=1./(1+25.*x2.^2);
figure(777)
title('Figure 777')
for loop=1:1:6

    subplot(6,2,loop);
    plot(x2,y2,'linewidth',2);
    hold on
    plot(x1,y1,'r.','markersize',25);
    hold on
end
%%%(A)
[p1,s1,u1] = polyfit(x1,y1,4);
Y1=polyval(p1, x2, s1, u1);
subplot (6,2,1)
plot(x2,Y1,'b','linewidth',6);

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

%%%(C)
Y3 = interp1(x1, y1, x2, 'linear');
subplot(6,3,1)
plot(x2, Y3, 'b', 'linewidth', 6);

%%%(D)
Y4 = interp1(x1,y1,x2, 'nearest');
subplot(6,4,1)
plot(x2, Y4, 'b', 'linewidth', 6);

%%%(E)
Y5 = interp1(x1,y1,x2, 'spline');
subplot(6,5,1)
plot(x2, Y5, 'b', 'linewidth', 6);

%%%(F)%%%(This method does not exist for Matlab R2017a)
Y6 = interp1(x1,y1,x2, 'makima');
subplot(6,6,1)
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
3

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

x2=-1:1001:1;

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.