Question: Create piecewise linear function from a given set of points

Hello,

how does one create a piecewise linear function from a given set of points? Having np points [x[i],y[i]], I tried

Lf(q):=q->piecewise(seq('(q>=x[j]) and (q<=x[j+1]),evalf(y[j]+(q-x[j])*(y[j+1]-y[j])/(x[j+1]-x[j]))',j=0..np-1),ERROR("argument out of range!"));

but it did not work (invoking Lf(3); resulted in "Lf(3)," not in an actual number). Then I tried

Lf(q):=q->convert(If(seq('(q>=x[j]) and (q<=x[j+1]),evalf(y[j]+(q-x[j])*(y[j+1]-y[j])/(x[j+1]-x[j]))',j=0..np-1)),piecewise,q);

which, again, did not work. I do not understand why this function assignment fails, because

convert(If(seq('(q>=x[j]) and (q<=x[j+1]),evalf(y[j]+(q-x[j])*(y[j+1]-y[j])/(x[j+1]-x[j]))',j=0..np-1)),piecewise,q);

produces the exact piecewise linear output I would like to obtain (except for the error message for arguments out of the range given by the points).

Thanks for any help.

 

Best regards,

nvx

Please Wait...