1
votes

I am trying to interpolate the following function using the MATLAB function spline,

enter image description here

at equidistant points xi = i./n, i = 0,1,...,n, and for n = 2^j, j = 4,5,...,14.

For each calculation, I record the maximum error at the points x = 0:0.001:1 and plot these errors against n using a loglog plot.

Below is the code,

index=1

for j = 4:1:14;
    n = 2^j;
    i = 0:1:n;
    xi = i./n;
    yi = ((exp(3*xi))*sin(200.*(xi.^2))) ./(1+20.*(xi.^2));
    x = 0:.001:1;
    ye = ((exp(3*x))*sin(200*x.^2)) ./(1+20*x.^2);
    yp = spline(x,xi,yi);
    err = ye - yp;
    merr(index) = max(err);
    index = index+1;
end

n1 = 10:10:170;
loglog(n1, merr,'.')
xlabel('n');
ylabel('errors');
title('Cubic Splines');

but when I run the code, I got the following error:

Error using * Inner matrix dimensions must agree.

Error in (line 9) yi = ((exp(3*xi))sin(200.(xi.^2))) ./(1+20.*(xi.^2));

I'm just starting learning MatLab, can anyone help?

1
Beware that errors are usually computed with a mean squared error or at least with an abs function. In your code, err = ye - yp and err = abs(ye - yp) give different results.marsei
Your 'loglog' command will throw an error because numel(n1)~=numel(merr) but other than that, I think my answer explains the error message you get and a spline error you will get.chappjc

1 Answers

1
votes

You want element-wise multiplication (.*) for the following part of code:

yi = ((exp(3*xi))*sin(200.*(xi.^2))) ./(1+20.*(xi.^2));

should be

yi = ((exp(3*xi)).*sin(200.*(xi.^2))) ./(1+20.*(xi.^2));

The same issue is present for the computation of ye.

When you use mtimes (*), MATLAB tries to do matrix multiplication, which in your case (1-by-n times 1-by-n) is invalid.

Then you will run into a problem with your spline command. Change it to yp = spline(xi,yi,x); so that the values at which you want to interploate (x) are the last argument.