该语句不在任何函数内

This statement is not inside any function

我在第 51 行(从 startw = input('Enter starting wavelength: ') 开始)收到一个解析错误,但我不知道为什么。错误是这样写的;行:51 列:1 此语句不在任何函数内。 (它跟在终止函数 "OpticalFunction" 定义的 END 之后。)在 Matlab 脚本上 运行 本身工作得很好。

function OpticalFunction
daq.reset
clear, close all
clc;
s = daq.createSession('ni'); 
% Creates the session object
s.addDigitalChannel('Dev1','Port0/Line0:7','OutputOnly');
% Adds 8 digital output channels (numbered 0:7) on the DAQ card

% The following creates the uicontrols
onoff = uicontrol('Style','togglebutton','String','go',...
'Position',[20 200 70 40],'Callback',@move_buggy);

forwards = uicontrol('Style','pushbutton','String','forwards',...
'Position',[20 150 70 40],'Callback',@go_forward);

backwards = uicontrol('Style','pushbutton','String','backwards',...
'Position',[20 100 70 40],'Callback',@go_backward);

nout = [51 102 204 153]; % decimal sequence for forward motion

% This is the callback function for the toggle button.
% It moves the buggy when the toggle button is pressed.
% 'hObject' is the handle for the uicontrol calling the function.
function move_buggy(hObject,eventdata)
   while hObject.Value == hObject.Max
       for n=1:4
       output_data=dec2binvec(nout(n),8);
       % high state=1 low state=0
       outputSingleScan(s,output_data);
       % outputs the data in output_data to the device
       pause(1.6) 
       % use this to change the speed of the motor
       end
   end
end
% These are the callbacks for the pushbuttons.
% They set the direction of travel for the motors.

   function go_forward(hObject,eventdata)
       nout = [51 102 204 153];
   end

   function go_backward(hObject,eventdata)
       nout = [153 204 102 51];
   end
end 

%%

startw = input('Enter starting wavelength: ');
deend = input('Desired final wavelength: ');
r = 11/62; % this is the rate of wavelegth change with time for GaAs
r = 29.5/66; %this is the rate of wavelenght change with time for GaP 
% comment off the r value not used

OpticalFunction
% calls on the function optical thing

错误信息很清楚:这是一个不在函数内部的语句。当M文件的第一条语句是function时,它是一个函数M文件,它定义了一个函数,不能包含任何函数外的语句。

如果你想有一个脚本M文件,你需要把脚本本身放在文件的顶部,任何局部函数都必须在底部定义。

这与 Octave 的做法完全不同,函数定义必须位于使用它的脚本行之前。 MATLAB 和 Octave 不能共享定义局部函数的脚本。解决方案是在单独的文件中定义函数。