Search code examples
matlabfunctionloopssavesymbolic-math

How to generate a function inside a script file in MATLAB


I am looking for a way to write a script file in MATLAB that generates a sequence of functions and save them each in a separate m-file.

More precisely, suppose you have a script file and you want to generates N different functions; something like this:

for i=1:N

  • Step 1: Do some symbolic calculation and find the expression of fi

  • Step 2: Define the function fi=fi(...)

  • Step 3: Save the the function in an m-file say fi.m

end

I myself have not found any clue so far. Here is two questions that if answered, such code then follows straightforwardly:

1. How to define a function in a script file and automatically save it in an m-file: Let say y=f(x)=x^2 is a symbolic relation calculated in a script file; how to automatically generate a function for it and save it in an m-file

2. How to use a string as a file name, function name, etc: Suppose you are creating an string "fi" in a loop for every i, and you want to use this string as a function name

Thanks for your help in advance


Solution

  • https://www.mathworks.com/help/symbolic/matlabfunction.html#bul5mb5-1

    If you want to convert symbolic functions to MATLAB function files, MATLAB has a function (called matlabFunction) that does exactly that.

    Example from that page:

    syms x y z
    r = x^2 + y^2 + z^2;
    f = matlabFunction(log(r)+r^(-1/2),'File','myfile');
    

    Which creates 'myfile.m':

    function out1 = myfile(x,y,z)
    %MYFILE
    %    OUT1 = MYFILE(X,Y,Z)
    t2 = x.^2;
    t3 = y.^2;
    t4 = z.^2;
    t5 = t2 + t3 + t4;
    out1 = log(t5) + 1.0./sqrt(t5);