这是我要执行的简单Matlab代码。
function result = scale(img, value)
result = value .* img;
end
dolphin = imread('dolphin.png')
imshow(scale(dolphin, 1.5));
错误提示:
Error: File: scale.m Line: 5 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function "scale".)
我在这里做错了什么?
答案 0 :(得分:5)
scale.m
是功能M文件,因为它以关键字function
开头。 end
之前的部分是函数的定义。当您在MATLAB命令行中调用scale
时,它将执行函数中的代码。 end
之后的内容不是该功能的一部分,因此无法执行。
如果打算编写仅在此脚本中使用的具有私有功能scale
的脚本,则将读取和显示dolphin
的代码行放在文件顶部。私有功能应位于脚本部分之后。 since MATLAB R2016b支持此语法。
否则,将dolphin
代码移动到另一个M文件,该文件将是没有任何函数定义的简单脚本M文件。然后,该脚本可以使用scale
,它将调用文件scale.m
中的函数。
将所有代码都保存在同一文件中的第三种选择是根本不使用脚本,而将脚本代码放在函数中:
function f % just a random name
dolphin = imread('dolphin.png')
imshow(scale(dolphin, 1.5));
end
function result = scale(img, value)
result = value .* img;
end
(函数名称不需要与文件名匹配,但是如果这些名称不匹配,则MATLAB编辑器会警告您。)