file - MATLAB 中的脚本和函数有什么区别?

标签 file function matlab

MATLAB 脚本文件和 MATLAB 函数文件有什么区别?

最佳答案

This page说,

Scripts versus Functions

Scripts are m-files containing MATLAB statements. MATLAB ``functions'' are another type of m-file. The biggest difference between scripts and functions is that functions have input and output parameters. Script files can only operate on the variables that are hard-coded into their m-file. As you can see, functions much more flexible. They are therefore more suitable for general purpose tasks that will be applied to different data.

Scripts are useful for tasks that don't change. They are also a way to document a specific sequence of actions, say a function call with special parameter values, that may be hard to remember.

There are more subtle differences between scripts and functions. A script can be thought of as a keyboard macro: when you type the name of the script, all of the commands contained in it are executed just as if you had typed these commands into the command window. Thus, all variables created in the script are added to the workspace for the current session. Furthermore, if any of the variables in the script file have the same name as the ones in your current workspace, the values of those variables in the workspace are changed by the actions in the script. This can be used to your advantage. It can also cause unwanted side effects.

In contrast, function variables are local to the function. (The exception is that it's possible to declare and use global variables, but that requires and explicit action by the user.) The local scope of function variables gives you greater security and flexibility. The only way (besides explicitly declared global variables) to get information into and out of a function is through through the variables in the parameter lists.

示例

脚本和函数之间的主要区别之一是对工作区中变量的访问。例如,假设在工作区中,您定义了两个变量 a = 10b = 20。这些变量在主提示符的命令行中定义。

脚本文件 - display_mult.m

disp(a*b);

键入 display_mult 将在工作区中显示 ab 的乘积,即 10*20200

但是如果你在一个同名文件中定义了一个名为 display_mult 的函数:

函数文件 - display_mult.m

function display_mult(a,b)
   disp(a*b);
end

您必须将这两个变量作为参数包含在函数调用中。因此,display_mult 这次将 工作,因为 ab 不存在于函数的工作区中。您必须通过运行 display_mult(a,b) 来包含它们,这将显示所需的结果。

简单说明

脚本中的每条语句都相当于在 MATLAB 的命令窗口中键入它们。您只是预先将它们存储在一个文件中!

另一方面,函数接受参数并且是一个"new"工作区,与主工作区分开。

注意:函数调用末尾的 end 是可选的,但我喜欢添加它以使事情井井有条。当然,如果您在一个文件中有多个函数定义,它们都必须以 end 结尾。此外,您不能在同一个文件中同时拥有脚本和函数定义。

关于file - MATLAB 中的脚本和函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695365/

相关文章:

matlab - 在Matlab中防止 “MATLAB:unassignedOutputs”

python - 删除括号内包含的文本

image - 如何使用 Nest.js 框架向客户端返回图像?

c++ - C++中函数的内存分配

javascript - 如何动态传递元素id并调用javascript函数?

c - 递归二进制搜索函数缺少什么? (C)

javascript - 显示所选文件的名称

file - Powershell脚本用来自不同文本文件的内容替换字符串,并保持换行

matlab - 如何在 MATLAB 中创建自定义 "Probability Distribution Object"

matlab - 使用线性分类器最小化训练误差