return a function without e.g. f(5)

3 views (last 30 days)
Marvin van Stegen
Marvin van Stegen on 30 Jun 2015
Edited: Thorsten on 2 Jul 2015
I have never used Matlab before so it really is difficult for me as I now have a task in math course that says to interpolate a function with Lagrange.
My problem has nothing to do with the interpolation itself, more a question if something is possible and if so, how.
E.g. I say
f = @(x) x^3;
and p = @(x) f(2)*x
Matlab display p exactly like above but i would want it to display it as
p = @(x) 8*x
as is wouldn't make much sense to have the result as a polynomial with f(...) as values.
so i hope someone can help me with that.

Answers (1)

Walter Roberson
Walter Roberson on 30 Jun 2015
If you have the symbolic toolbox,
syms x
p = matlabFunction(f(2)*x, x);
You did well, by the way, to realize that it was a matter of what was displayed rather than a matter of how it would execute.
  4 Comments
Marvin van Stegen
Marvin van Stegen on 2 Jul 2015
Edited: Marvin van Stegen on 2 Jul 2015
wow, that is easier than expected. can i ask you more specific things like how i can reduce the error of the interpolation?
currently my code looks like this:
function p = makeLagrangePoly(f,a,b,n)
syms x
X = zeros(1,n+1);
Y = zeros(1,n+1);
L = zeros(1,n+1);
x_k = a + k(b-a)/n
for k = 0:n
X(1,k+1) = a + (k/n)*(b-a);
Y(1,k+1) = f(a + (k/n)*(b-a));
end
t = @(x) 0;
for k = 1:n+1
l = @(x) 1;
for j = 1:n+1
if k ~= j
l = @(x) (l(x).*(x-X(1,j))/((k-j)*(b-a)/n));
end
end
t = @(x) (t(x) + Y(1,k).*l(x));
end
p = expand(t(x));
do you know a way to make the approximation better?
I realized by now, that i don't really need L, so i will delete that part.
Thorsten
Thorsten on 2 Jul 2015
Edited: Thorsten on 2 Jul 2015
Walter has answers two of your questions; I think it would be better to accept the answer and ask a new question in the forum with a new title for the new question.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!