0

I'm trying to plot a piecewise function as an interpolation for the function f(x) = 1/(1+25x^2). This is how I plotted two functions previously when I wasn't dealing with piecewise.

z = linspace(-1,1,200);
yexact = 1./(1+25.*z.^2);
plot(z,yexact)

N=2;
x = size(N+1);
for i = 1:(N+1)
x(i) = -1+(1+cos(((2*i+1)*pi)/(2*(N+1))));
end
a = polyfit(x,1./(1+25.*x.^2),N);
yinter = polyval(a,z);
plot(z,yexact,z,yinter);
title('N = 2');
legend('exact','interpolation');

This was done for N = 2, 5, 10, 15, 20, 30. Now I need to change this to work for piecewise with the same N values. The x(i)'s are the intervals and the P(i)'s are the slopes of the piecewise function. So for N = 2, I need to plot P(1) from x(1) to x(2) and P(2) from x(2) to x(3).

N=2;
x = size(N+1);
P = size(N);
for i = 1:(N+1)
    x(i) = -1 + 2*i/N;
end
for i = 1:N
    P(i) = (1/(1+25*(x(i)).^2)) + ((i-1-x(i))/(x(i+1)-x(i)))*((1/(1+25*(x(i+1)).^2))-(1/(1+25*(x(i)).^2)));
end
Matt Robbins
  • 429
  • 2
  • 5
  • 10
  • [`hold`](https://www.mathworks.com/help/matlab/ref/hold.html) – sco1 Feb 07 '18 at 04:35
  • 1
    Possible duplicate of [Multiple plots in one figure](https://stackoverflow.com/questions/8772947/multiple-plots-in-one-figure) – sco1 Feb 07 '18 at 04:36
  • I don't think this is a duplicate, because it's really the piecewise aspect that I don't understand am asking about, which isn't mentioned in the Multiple plots in one figure question. – Matt Robbins Feb 07 '18 at 04:41
  • 1
    Each of your "pieces" is a new plot, so treat them accordingly and you'll be sorted – Wolfie Feb 07 '18 at 08:22

1 Answers1

0

All you have to do is to define your N values as a vector and, then, iterate over it. Into each iteration, the result returned by the computation over the current N value is plotted over the existing axis (for more information, visit this link of the official Matlab documentation).

Here is an example:

z = linspace(-1,1,200);
yexact = 1./(1+25.*z.^2);
plot(z,yexact);

hold on;

for n = [2 5 10]
    x = size(n+1);
    for i = 1:(n+1)
    x(i) = -1+(1+cos(((2*i+1)*pi)/(2*(n+1))));
    end
    a = polyfit(x,1./(1+25.*x.^2),n);
    yinter = polyval(a,z);

    plot(z,yinter);
end

hold off;

And here is the resulting output:

Output

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98