cerv21
cerv21

Reputation: 433

Matlab: Put a sum into a function

I would like to approximate numerical data by a function:

f = @(a0,xdata) a0(1).*xdata + ... + a0(n) .* xdata.^n

How can I do that, since a for loop does not work in a function? I know there is an internal polynomial function, but since I might want to extend the sum to non-integer exponents, I want to write my own function.

Upvotes: 2

Views: 107

Answers (1)

Alex Taylor
Alex Taylor

Reputation: 1412

f = @(a0,xdata) sum(a0 .* xdata.^(1:length(a0)));

If you insist on writing this as anonymous function, but I'd recommend writing this as a function on multiple lines with a function body:

function out = f(a0,xdata)
    exponents = 1:length(a0);
    out = sum(a0 .*xdata .^ exponents);
end

Upvotes: 7

Related Questions