gpt4 book ai didi

matlab - MATLAB问题与异常处理

转载 作者:行者123 更新时间:2023-12-03 07:46:34 24 4
gpt4 key购买 nike

我试图优雅地处理异常,以便当用户输入字符,期望输入数字时,系统会通过自定义警告/消息通知他。

我知道try,catch具有以下语法:

try
statements
catch exception
statements
end

我一直在尝试这样的事情,但无济于事:
number = input('Enter number'); 
try
assert(isnumeric(number));
catch ME
warning('NOT A NUMBER');
end

我不明白为什么上面的代码会失败,因为 assert如果为false,则会显示错误消息“Assertion Failed”。

我知道使用 trycatch有点像大锤,但是我想了解如何实现上述功能。任何提示将不胜感激。

最佳答案

从帮助命令:

input Prompt for user input.

RESULT = input(PROMPT) displays the PROMPT string on the screen, waits for input from the keyboard, evaluates any expressions in the input, and returns the value in RESULT. To evaluate expressions, input accesses variables in the current workspace. If you press the return key without entering anything, input returns an empty matrix.



因此,如果用户输入“山羊”,MATLAB将尝试评估名为“山羊”的变量。这对这个问题没有帮助。

但是,进一步查看帮助命令:

STR = input(PROMPT,'s') returns the entered text as a MATLAB string, without evaluating expressions.



这才更适合您的问题。
number = input('Enter number', 's');
try
assert(~isnan(str2double(number)));
catch ME
warning('NOT A NUMBER');
end

关于matlab - MATLAB问题与异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49866593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com