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

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)

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

thanks for your answer! that helped me a great bunch. i think it is kinda obvious that I tested if the execution would work dispite the display issue, maybe that's just me though.
i have another question for you, if you don't mind. while i can now display the polynomial in a way that is acceptable, I lack in another area.
p = @(x) (x+2)*(x-1) or something else, but you get the idea. is there another function built-in that displays that as x^2 + x -2?
i have the hinch that i'm doing the task in a way that is way too complicated :(
syms x
p = matlabFunction( expand( (x+2)*(x-1) ), x);
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.

Asked:

on 30 Jun 2015

Edited:

on 2 Jul 2015

Community Treasure Hunt

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

Start Hunting!