Reputation:
Let's say I want to create a rational fraction function in GNU Octave. Can I do it easily using polynomial coefficients?
As example I would like to build
f = @(x) x.^2./(2*x^2+3*x+2)
using
p1 = [1 0 0]
p2 = [2 3 2]
Upvotes: 1
Views: 281
Reputation: 10792
You could also use the built-in function polyval
:
p1 = [1 0 0]
p2 = [2 3 2]
f = @(x,p1,p2) polyval(p1,x)./polyval(p2,x)
Upvotes: 4
Reputation: 35525
With:
p1 = [1 0 0]
p2 = [2 3 2]
You can either do
f = @(x) sum([x.^2, x, 1].*p1) ./sum([x.^2, x, 1].*p2);
or
f = @(x,p1,p2) sum([x.^2, x, 1].*p1) ./sum([x.^2, x, 1].*p2);
I'd say the second one is clearer if you are going to be trying different polynomial coefficients.
if you want to have flexibility on the order of the polynomials, then you can even go further :
f = @(x,p1,p2) sum(x.^[length(p1):-1:0].*p1) ./sum(x.^[length(p2):-1:0].*p2);
Upvotes: 2