Matlab: creating a symfun array

I was trying to create an array symfun

so that I can later access these functions and perform a diff

wrt operation on specific variables, I searched and found code like:

syms x
f = symfun([x1^2+x2-x3; x2+x3^2; x1*x2], x);

      

But that's not what I'm looking for, this snippet creates symfun

from an array, but I need to create an array symfun

. So if I have n

symfun

one stored in an array as well as variables n

stored in an array then you want to create a matrix with the following rule:

[[diff(func_1, x1)    diff(func_1, x2) ...... diff(func_1, xn)]
 [diff(func_2, x1)    diff(func_2, x2) ...... diff(func_2, xn)]
  .
  .
  .
  .
 [diff(func_n, x1) .......................... diff(func_n, xn)]]

      

And here is my code:

function[K] = bigPopaPump()
x1 = sym('x1')
x2 = sym('x2')
f1 = symfun(3*x1+2, x1)
f2 = symfun(8*x2+5, x2)
funcs = [f1, f2]
xess = [x1, x2]
dummy_array = zeros(2, 2)
for i = 1:size(funcs)
    for j = 1:size(funcs)
        dummy_array(i, j) = diff(funcs(i), xess(j));
    end
end
display dummy_array
end

      

+3


source to share


1 answer


I guess what you mean

syms x1 x2 x3
f = symfun([x1^2+x2-x3; x2+x3^2; x1*x2], [x1 x2 x3])

      

which returns

f(x1, x2, x3) =

 x1^2 + x2 - x3
      x3^2 + x2
          x1*x2

      

Likewise, this returns identical output:

syms x1 x2 x3
f = [symfun(x1^2+x2-x3, [x1 x2 x3]);
     symfun(x2+x3^2, [x1 x2 x3]);
     symfun(x1*x2, [x1 x2 x3])]

      

If you want an array symfun

, you will need to use a cell array . The reason for this is that a symfun

is an efficient function descriptor. You need to use cell arrays, not arrays, to group function descriptors .

In your example:



syms x1 x2 x3
f = {symfun(x1^2+x2-x3, [x1 x2 x3]);
     symfun(x2+x3^2, [x1 x2 x3]);
     symfun(x1*x2, [x1 x2 x3])}

      

or

syms x1 x2 x3
f = arrayfun(@(fx)symfun(fx,[x1 x2 x3]),[x1^2+x2-x3; x2+x3^2; x1*x2],'UniformOutput',false)

      

returns

f =

    [1x1 symfun]
    [1x1 symfun]
    [1x1 symfun]

      

Then you can evaluate the first function, for example through f{1}(2,3,4)

.

See also this related question .

+1


source







All Articles