1

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

4
  • What have you tried so far? It should be very straightforward to translate what you've written to code Commented Jan 21, 2017 at 23:04
  • No it is not. First, how could you write a simple function in a script file and tell it to save the function in an m-file? Second, How are you gonna define a function while you are not the one who has calculated the function and has written it? Commented Jan 21, 2017 at 23:14
  • I don't understand much of what you just said, but that leads be to believe that this question is too broad. Please consider rephrasing it and showing what you've tried so far. See How to Ask Commented Jan 21, 2017 at 23:16
  • The question has been modified. Commented Jan 22, 2017 at 0:08

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.