Search code examples
matlabanonymous-functionfunction-handle

Creating anonymous function handle dynamically in MATLAB using numeric matrices as sources


I'm kinda lost in a problem where I need to (dynamically) create an anonymous function handle from huge matrices and 192 variables.

I'll try to give you an (easier) example of what I have to do and what I have in mind to achieve it (but without a clue how to do it in MATLAB ):

syms x1 x2 x3 x4 real
X = [x1 x2 x3 x4]'
F = [1 2 3 4; 1 2 3 4]
Y = [9 8]'
my_fun = (F*X + Y)' * (F*X + Y)
%solve my_fun to min for X

So, this is what I want to have (my_fun).

The thing is, that there will be x1 to x192, F will be like 10000x192 and Y like 10000x1. Using symbolic tb is very slow and since I later have to calculate the Hessian it is superdupser slow.

I now found a way to numerically calculate the Hessian (from MATLAB file exchange) but have no clue, how to calculate my_fun as an (anonymous) function. I simply lack the skills of MATLAB + function handles. I already tried several things.

So, I think what I need to know is how to create X dynamically with x(1) to x(192) and then calculate my_fun = @(x) ...

EDIT: Thanks for the edit :) The only thing that I can think of to solve this is by using a couple of loops to create the anonymous function handle as a string and then use str2fun, but I feel like this isn't the easiest way to get what I need :)


Solution

  • First of all: Delete your first two lines containing stuff from the symbolic toolbox. You won't need any of this.

    You have two options:

    Using a function-file:

    These would be the contents of the file my_fun.m:

    function result = my_fun(X)
       F = [1 2 3 4; 1 2 3 4];
       Y = [9 8]';
       result = (F*X + Y)' * (F*X + Y);
    

    You would then pass this function as an argument using @my_fun.

    Using an anonymous function

    You could define a function handle using an anonymous function using:

    F = [1 2 3 4; 1 2 3 4];
    Y = [9 8]';
    my_fun = @(X) (F*X + Y)' * (F*X + Y);
    

    This will capture the current contents of your local variables Fand Y. So changing F or Y afterwards won't change my_fun. In contrast to the above version you will pass this using my_fun.