Search code examples
matlabsymbolic-computation

Use symbolic matlab for flexible number of arguments and functions


I have a function F which takes as an input a vector a. Both the output of the function and a are vectors of length N, where N is arbitrary. Each component Fn is of the form g(a(n),a(n-k)), where g is the same for each component.

I want to implement this function in matlab using its symbolic functionality and calculate its Jacobian (and then store both the function and its jacobian as a regular .m file using matlabFunction). I know how to do this for a function where each input is a scalar that can be handled manually. But here I want a script that is capable of producing these files for any N. Is there a nice way to do this?

One solution I came up with is to generate an array of strings "a0","a1", ..., "aN" and define each component of the output using eval. But this is messy and I was wondering if there is a better way.

Thank you!

[EDIT]

Here is a minimal working example of my current solution:

function F = F_symbolically(N)

%generate symbols
for n = 1:N
    syms(['a',num2str(n)]); 
end

%define output
F(1) = a1;
for n = 2:N
    F(n) = eval(sprintf('a%i + a%i',n,n-1));
end

Solution

  • Try this:

    function F = F_symbolically(N)
        a = sym('a',[1 N]);
        F = a(1);
        for i=2:N
            F(i) = a(i) + a(i-1);
        end
    end
    

    Note the use of sym function (not syms) to create an array of symbolic variables.