What is the correct way to add recursive functions and see the correct output after printing it?

This is what I tried:

f = @(x) 0;
for i = 1:n
    f = @(x) f(x) + x^i;
end

Everything seems to be correct when I test it by adding some values.

But when print f, I got this outputf = @(x) f(x) + x^i

EDIT: How can I get the output that I want to see where all the terms appear in the function descriptor when I print f.

+4
source share
2 answers

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
+5
source

for, sum,

f =@(x,n) sum(x.^(1:n));

Edit:

OP , sum(x^i). , x,

g = @(x,n) sum(reshape(repmat(x(:), 1, n).^repmat(n, numel(x), n), horzcat(size(x), n)), length(size(x)) + 1);
-1

All Articles