You can use symbolic functions ( symfun) to do what you want:
% create symbolic variable
syms x
% define order of polynom
n = 3;
% create polynom
fs(x) = 0*x;
for i = 1:n
fs(x) = fs(x) + x.^i;
end
% convert symbolic function to function handle
f = matlabFunction(fs)
Results in:
f =
@(x)x+x.^2+x.^3
Edit: The following is an approach without using the Symbolic Math tool:
% define order of polynom
n = 3;
% create polynom as string
fstring = '0';
for i = 1:n
fstring = [fstring, '+x.^',num2str(i)];
end
f = str2func(['@(x)',fstring]);
Results in:
f =
@(x)0+x.^1+x.^2+x.^3
source
share