Run script either within another script or as standalone

2 次查看(过去 30 天)
Hello,
I have an algorithm that produces some matrices and another algorithm that produces figures based on these matrices. The first algorithm saves the relevant matrices.
Sometimes I'd like to run both algorithms one after the other, sometimes I only want to run the second algorithm using as inputs some saved matrices.
Currently, I have to manually comment in and out a few lines at the beginning of the second algorithm, depending on whether I want to run it as a standalone script or a script within script 1. For instance, if I want to run it as a standalone script, then clear the workspace and load in some matrices from a path that I specify. If I want to run it within script 1, I comment out those lines
Is it possible that matlab recognizes whether script 2 is called from script 1 or not and based on that information, use an if statement?
Thanks!
  5 个评论
Rik
Rik 2022-9-27
Why? You already have two files, why not make both a function?
You shouldn't use scripts for serious work. Anything beyond quick debugging deserves a documented interface, which a function allows you to do.
Adam Danz
Adam Danz 2022-9-27
If you prefer working within a script and without functions, instead of commenting/uncommenting, you can create flag variables toward the top of the script to determine what sections shoud be run and then put each section within conditional statements that executes only when the flag indicates that it should run.
Example:
runAlgo1 = true;
runAlgo2 = false;
if runAlgo1
<your code>
end
if runAlgo2
<your code>
end
Instead of commenting/uncommenting lines, you just need to set the values of the flags.
However (here comes the warnings)
  • This often leads to reproducibility problems. The results depend on how you set the flags so if you save or plot any data, the flag values should be saved or documented within the figures so you can recreate them.
  • Susceptible to fat-finger errors. Pressing 9 instead of 0 to enter a logical value will result in unintended results. You could validate the flags but if you do that, why not just use functions instead?
  • This isn't user-friendly. If someone else uses your code (including your future-self) it may not be clear that the flags even exist without reading through the code.
  • It's a bit sophmoric and suggests that the analysis is disorganized and quickly thrown together rather than having a design that was carefully thought-out. I've written this kind of script before as a means of getting a small project started but if the project lasts longer than a couple of days, the script needs to evolve into a function as others have suggested.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by