如何在 MatLab 中为我的用户输入函数添加 "catch all" 项?

How do I add a "catch all" term for my user input function in MatLab?

我正在 MatLab 中创建一个函数,提示用户输入,然后根据该输入显示一条消息。有效输入(1-10 的整数)将显示 'Input recorded' 消息(这是有效的),任何其他输入(即非整数值、范围外的整数或文本)应显示 'Invalid input, try again',然后再次提示用户输入。 这是目前的功能:

n = 0;
while n == 0
    userInput = input('Input an integer from 1 - 10\n');
    
    switch userInput
        case {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
          disp('Input recorded');
          n = 1;
        otherwise
          disp('Invalid input, try again')
          pause(2);
          n = 0;
    end
end

目前,范围内的整数输入会触发确认消息并跳出 while 循环,任何其他数字输入都会触发我的 'Invalid input' 消息并再次循环,但是,文本输入(例如“五”)给我一条 MatLab 错误消息(包括我的控制台 window 输出的图像)。如何让 switch 语句也接受文本输入,以避免在用户键入文本时破坏我的代码?

显然我目前正在为此使用 switch,但我确信可能有更好的解决方案 if, elseif 声明 - 我对任何解决方案都持开放态度完成任务!

如果您使用仅带一个参数的 input,MATLAB 会尝试计算输入中的任何表达式。因此,如果有人提供输入,例如'a',MATLAB 将在您当前工作区的变量中搜索 'a'。由于没有使用该名称定义的变量,MATLAB 将抛出异常。 这就是为什么您必须将 input 中的格式指定为第二个参数的原因。我建议您定义指定格式 string,然后输入可以是任何内容。然后将字符串转换为double number,开始检查输入:

n = 0;
while n == 0
    userInput = input('Input an integer from 1 - 10\n','s'); %Read input and return it as MATLAB string
    userInput = str2double(userInput);
    
    if (~isnan(userInput) && ...               %Conversion didn't fail AND
        mod(userInput,1) == 0 &&...            %Input is an integer AND
        userInput >= 1 && userInput <= 10)     %Input is between 1 AND 10
        
        disp('Input recorded');
        n = 1;

    else   
     
        disp('Invalid input, try again')
        pause(2);
        n = 0;

    end
end