re-utilizing a piece of code within several functions

2 views (last 30 days)
Dear All!
I have a big initialization section which I wish to use within several matlab functions. If I run this section as a script whithin a function, it does not work. If a write this part as a function, it makes a mess as it returns dozens of variables.
Is there a way to include this part into a function without passing parameters? Something like
include('init.m')
or so. Thanks Dmitry
  2 Comments
Stephen23
Stephen23 on 10 Aug 2015
Why does it "not work" as a script? What error messages are you getting?
Dmitry Gromov
Dmitry Gromov on 10 Aug 2015
Edited: Dmitry Gromov on 10 Aug 2015
Stephen, please see my response to Walter's answer below.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 10 Aug 2015
run('init.m')
exists but expects a script, and is the same thing as
init
(except that run() can be given a path to a .m and will change directories to be able to execute it.)
If running the script "does not work" then run() will not work either.
  3 Comments
Walter Roberson
Walter Roberson on 10 Aug 2015
If you are not using nested functions, remove the "end" that corresponds to each "function" statement and the result will be something you can "poof" variables into existence in.
If you are using nested functions, then you cannot do that in any function in the same file that you define the nested function in.
Using an "end" matching "function" is a special guarantee to the parser that there is no hidden creation of variables; when the parser knows that it can make more efficient code. When you do have hidden creation of variables then you cannot do that if you have an "end" matching the "function". Nested functions are incompatible with the hidden creation of variables.
Dmitry Gromov
Dmitry Gromov on 10 Aug 2015
Walter, thank you for the detailed answer. Now, at least, I see the alternatives and will think how to optimize the structure of my programs.
D.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 10 Aug 2015
While you CAN do what Walter suggested, "poofing" variables like that can be dangerous either to operation of your program or to your sanity when you need to debug it. You could have a program that hasn't changed in a year but still fails because of a change to some other program.
I recommend instead that you write a function that returns a struct array containing the data you need to initialize or a class with properties that have those names. This encapsulation into a struct or object will allow you to add data to your initialization routine without risking overwriting a variable name used by one of the functions that call your initialization routine.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!