How to code the linear Splines function?

Hi all, I am getting stuck with the code of linear Splines function. The error is: "Unable to perform assignment because the indices on the left side are not compatible with the size of the right side" I appreciate for any help. Thanks!
if true
% code
function out=LSplines(x,pointx,pointy)
n=length(pointx);
for i=2:n
t1(i)= (pointx(i)-x);
b1(i)= (pointx(i)-pointx(i-1));
t2(i)= (x-pointx(i-1));
b2(i)= (pointx(i)-pointx(i-1));
end
P==0;
for i=2:n
P(i)= P(i)+pointy(i-1)*t1(i)/b1(i)+pointy(i)*t2(i)/b2(i)
end
end
end

Answers (1)

madhan ravi
madhan ravi on 12 Nov 2018
Edited: madhan ravi on 12 Nov 2018
function out=LSplines(x,pointx,pointy)
n=length(pointx);
for i=2:n
t1(i)= (pointx(i)-x);
b1(i)= (pointx(i)-pointx(i-1));
t2(i)= (x-pointx(i-1));
b2(i)= (pointx(i)-pointx(i-1));
end
P=cell(1,n);
P{1}=0;
for i=2:n
P{i}= P{i-1}+pointy(i-1)*t1(i)/b1(i)+pointy(i)*t2(i)/b2(i);
end
out=P;
end

8 Comments

Thank you! Madhan, Still having error, "Error in LSplines (line 5)
t1(i)= (pointx(i)-x);" This part cause to be incompatible of right and left side.
provide your datas
Ni Su
Ni Su on 12 Nov 2018
Edited: madhan ravi on 12 Nov 2018
Data is: Write a Mat lab function which will take in n data points and an x value and produce the y value corresponding to the linear spline approximation. Plot the linear spline through the points:(-2,1),(-1.5,3),(-1,0),(-0.5,2),(0,3),(0.5,2),(1,-4),(1.5,7),(2,-1). Thank you!
madhan ravi's reply: so what's x , pointx and pointy in your function?
Ni Su
Ni Su on 12 Nov 2018
Edited: madhan ravi on 12 Nov 2018
pointx: is a vector of x value through the given points:[-2 -1.5 -1 -0.5 0 0.5 1 1.5 2],and same for pointy:[1 -3 0 2 3 2 -4 7 -1],
madhan ravi's reply : what's x?
x is the values that we use to plot it out (help the line smoother): for example:x=[-3:0.01:3], and y is the corresponding values of x with the Splines function.
this code is working, some issues happen when I try to plot it out.
function P=LSplines(x,pointx,pointy)
n=length(pointx);
P=cell(1,n);
P{1}=0;
for i=2:n
P{i}= P{i-1}+pointy(i-1)*(pointx(i)-x)/(pointx(i)-pointx(i-1))+pointy(i)*(x-pointx(i-1))/(pointx(i)-pointx(i-1));
end
end
The main code to plot out and the error is:"Invalid data argument"
if true
%Maincode
pointx = input('Enter the vector of x points: \n');
pointy = input('Enter the vector of y points: \n');
x = [min(pointx)-1:0.1:max(pointx)+1];
y = LSplines(x,pointx,pointy);
plot(pointx,pointy,'r*');
hold on
plot(x,y,'b')
end

Sign in to comment.

Asked:

on 12 Nov 2018

Edited:

on 12 Nov 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!