How can I create a function that returns a function?

19 views (last 30 days)
I'm tryng to create a function that returns to me the interpolation polynom of newton. This is the code:
function Y=newton(x,y)
syms X;
n=length(x);
b=zeros(n,n);
b(:,1)=y(:);
%finite difference matrix
for j=2:n
for i=1:n-j+1
b(i,j)= (b(i+1,j-1)-b(i,j-1))/(x(i+j-1)-x(i));
end
end
%interpolation polynom
yint=b(1,1);
xt=1;
for j=1:n-1
xt=xt*(X-x(j));
yint=yint+b(1,j+1)*xt;
end
Y=yint
It's already working, but I want the output to be a function, so I can calculate it's value in any point, make graphics, etc.
  2 Comments
Vitor Pessoa
Vitor Pessoa on 14 Aug 2016
Edited: Geoff Hayes on 14 Aug 2016
function Y=newton(x,y)
syms X;
n=length(x);
b=zeros(n,n);
b(:,1)=y(:);
%finite difference matrix
for j=2:n
for i=1:n-j+1
b(i,j)= (b(i+1,j-1)-b(i,j-1))/(x(i+j-1)-x(i));
end
end
%interpolation polynom
yint=b(1,1);
xt=1;
for j=1:n-1
xt=xt*(X-x(j));
yint=yint+b(1,j+1)*xt;
end
Y=yint
Sorry, it was supposed to come out like this.
Geoff Hayes
Geoff Hayes on 14 Aug 2016
Vitor - to properly format your code, highlight that text which is code and press the {}Code button.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 14 Aug 2016
Functions cannot return functions. Functions can return function handles, and functions can return symbolic expressions, and functions can return symbolic functions. The Y that you compute is already a symbolic expression; if you want to turn it into a function handle, use matlabFunction

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!