How to put a script into another script

45 次查看(过去 30 天)
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!

回答(1 个)

Stephen23
Stephen23 2015-4-11
编辑:Stephen23 2015-4-11
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 个评论
Stephen23
Stephen23 2017-12-8
编辑:Stephen23 2017-12-8
@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:

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by