如何在用户输入错误时退出matlab m文件(而不是整个matlab)?
我知道如果m文件在运行时出错,我们可以按Ctrl-C停止它。但是我需要一个命令将其放入我的m文件中,以便在发生错误时执行此操作。
请不要建议使用“exit”或“quit”命令,因为它们会终止整个matlab,而我不想这样做。
请不要建议使用“exit”或“quit”命令,因为它们会终止整个matlab,而我不想这样做。
error
函数似乎是你需要的。y = input('Please input a non-negative number: ');
if(y<0)
error('input must be non-negative');
end
disp( sprintf('y=%f', y ) );
嘿,我想你可以使用try-catch组合来处理一些意外错误并采取相应措施。
举个例子,
function [ output ] = test(input)
Bmat = [ 1 1 1 ] % Some matrix
try
input*B;
catch ME
disp(ME.message)
return; % This is the statement that exits your function
end
end
如果您运行
>> test([1 1 1])
return
命令可以正常工作,但如果有多个输出,则会提示错误消息。我想这只是 Matlab 的设计不够好吧。 - Argyll您可以像这样输入一个错误命令 error('bad user input'),它将停止脚本的运行。
编辑:或者,您可以重构代码,除非您将输入标志设置为 true,否则不会运行。例如:
inp = input('>', s)
if validateInput(inp)
%do you stuff here or call your main function
else
fprintf('Invalid input')
end
error
并不是最佳选择。它会阻止像lasterror
这样的东西完全工作。此外,参数中的特殊字符,如'\n'
,也不会被转换。 - horchler