PDA

查看完整版本 : MATLAB脚本代码和功能代码在同一文件中?


poster
2019-12-14, 20:46
可能重复:
在MATLAB中,可以在同一文件中包含脚本和函数定义吗? (https://stackoverflow.com/questions/5363397/in-matlab-can-i-have-a-script-and-a-function-definition-in-the-same-file)

我可以在同一文件中包含MATLAB脚本代码和功能代码吗?

%% SAVED IN FILE myfunc.m (otherwise fail) function [out1] = myfunc( x ) out1 = sqrt( 1 + (cos(x))^2 ); end %% %OTHER CRAP y = 1:10 % use myfunc 即使使用end关键字,它似乎也不起作用。是否允许这种类型的事物?我是否始终需要在其自己的正确命名的文件中具有EACH功能?

我确定几年前我在同一文件中看到了使用这些功能的函数和代码。



回答:

如果m代码中包含函数,则所有代码都必须由函数封装。 入口点函数的名称应与filename匹配 。如果您考虑一下,这是有道理的,因为它有利于代码重用。

您可以尝试以下方法:

文件名:myScript.m

function [] = myScript() y = 1:10; out1 = myfunc(y); end function [out1] = myfunc( x ) out1 = sqrt( 1 + (cos(x))^2 ); end 然后,您可以按F5键,或在matlab命令提示符下键入myScript



更多&回答... (https://stackoverflow.com/questions/5394494)