0

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
Scipio
  • 313
  • 2
  • 15
  • 1
    Please put some example code into your question to demonstrate your problem, either a version for a fixed number of arguments or your `eval` solution. I am sure it can be done better, but I don't know if I need to explain comma separated lists, how the symbolic toolbox deals with vectors or both. – Daniel Mar 19 '16 at 12:11
  • 2
    [Do not use dynamic variable naming](http://stackoverflow.com/a/32467170/5211833) it's bad. MATLAB has several data container formats which are highly suited to this task, like structures. – Adriaan Mar 19 '16 at 12:11
  • 1
    are you aware of the syntax: `a = sym('a',[1 N])` which can then be accessed as `a(i)`? – Amro Mar 19 '16 at 12:22
  • Thank you for responses. @Daniel, I added a minimal working example. Adriaan, I completely agree, hence my question ;) The question you linked is definitely interesting but I don't find anything about symbolic functionality. Do you have any sample of how to do what I do above without eval? – Scipio Mar 19 '16 at 12:24
  • @Amro no I was not :P That does the trick! Thank you! – Scipio Mar 19 '16 at 12:27

1 Answers1

2

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.

Amro
  • 123,847
  • 25
  • 243
  • 454
  • Not sure how representative the OP's example is, but function body could be replaced by `F = cumsum(sym('a',[1 N]));`. – horchler Mar 19 '16 at 16:08
  • 1
    Not quite, the function above is computing the sum of current and previous terms only, not cumulatively all the way to beginning.. Anyway vectorization is not the main concern here, I'm sure we can do it with something like F = [a(1), a(1:end-1)+a(2:end)] – Amro Mar 19 '16 at 22:04