Returning polynomial coefficients from matlabFunction as an array

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Returning polynomial coefficients from matlabFunction as an array

iceman
Using symbolic math I generate a polynomial using poly2sim in the following way :

nOrderA=input('Power of=')
A = sym('A', [1 nOrderA])
p = poly2sym(A,x)

This returns a polynomial the order of which is dependent on the user input. In the case of the user input being 3 the output of p is given by

p = (sym)

       2
  A₁₁⋅x  + A₁₂⋅x + A₁₃

I intend to use this output as a function and do this as follows:
F = matlabFunction((p))

This value of F returned is

@(A11, A12, A13, x) A11 .* x .^ 2 + A12 .* x + A13

Here instead of the coefficients A11, A12, A13 as separate inputs to the functions, I would like to have them inputted as an array of coefficients i.e.

the value of F returned should be

@(A, x) A11 .* x .^ 2 + A12 .* x + A13
where  A = [A11,A12,A13]

How should I go about doing this ?
Reply | Threaded
Open this post in threaded view
|

Re: Returning polynomial coefficients from matlabFunction as an array

Colin Macdonald-2
On 25/08/16 04:50, iceman wrote:
> the value of F returned should be
>
> @(A, x) A11 .* x .^ 2 + A12 .* x + A13
> where  A = [A11,A12,A13]
>
> How should I go about doing this ?

Here's one approach using num2cell:

 >> tmp = function_handle(p)
tmp =

@(A11, A12, A13, x) A11 .* x .^ 2 + A12 .* x + A13

 >> F = @(A,x) tmp(num2cell(A){:}, x)
F =

@(A, x) tmp (num2cell (A) {:}, x)

 >> F([5, 7, 11], x)
ans = (sym)

      2
   5⋅x  + 7⋅x + 11

 >> F([5, 7, 11], 2)
ans =  45

This has some overhead, so maybe there is a better way.

Colin

_______________________________________________
Help-octave mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/help-octave