How to put a script into another script
143 views (last 30 days)
Show older comments
Hi, I've written a for loop called My_Factorial.m and I want to put it into a new script file.
For example: the equation is x^n/n!
but i want to put the script I've developed in My_Factorial.m into the n! in the equation. (so it would result in: x^n/My_Factorial.m) Any tips would be great!
0 Comments
Answers (1)
Stephen23
on 11 Apr 2015
Edited: Stephen23
on 11 Apr 2015
You can simply call a script by its filename. So if we have this single lines of code in a script named sqrA:
B = A .^ 2;
we can call it from another script simply by calling its filename:
A = 1:4;
sqrA
disp(B)
which displays this in the command window:
1 4 9 16
Although this is obviously a pretty silly example, and calling such simple scripts like these ones is not recommended. Instead you should learn about functions, which are much more versatile, and allow control over the input and output arguments. You can also put multiple functions in one file, whereas you can only have one script per file.
If you are not sure what a function is, then read about the differences between scripts and functions.
You should probably work through these tutrials, which cover most of these basic concepts in MATLAB:
3 Comments
Stephen23
on 8 Dec 2017
Edited: Stephen23
on 8 Dec 2017
@work wolf: scripts are fun for playing around with, but should be avoided for code that you want to be robust and reliable. Beginners write scripts because they are easy. Experts write functions because they help to make code work reliably. Functions offer many advantages, including:
- JIT code acceleration,
- inputs and outputs are easy to manage,
- multiple functions per file,
- independent workspaces.
Because a function acts as a black-box operation, only defined by its specified inputs and outputs, then its internal steps, variables, or particular algorithm are irrelevant. This allows code to be broken into testable parts that are only defined by their functionality. Functions should be well documented and well tested.
Read more here:
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!