How to put a script into another script

조회 수: 45 (최근 30일)
Karen
Karen 2015년 4월 11일
댓글: work wolf 2017년 12월 8일
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:
work wolf
work wolf 2017년 12월 8일
Many thanks. full answer :).

댓글을 달려면 로그인하십시오.

카테고리

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