Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我如何加上一句;“一网打尽”;MatLab中用户输入函数的术语?_Matlab_User Input - Fatal编程技术网

我如何加上一句;“一网打尽”;MatLab中用户输入函数的术语?

我如何加上一句;“一网打尽”;MatLab中用户输入函数的术语?,matlab,user-input,Matlab,User Input,我正在MatLab中创建一个函数,提示用户输入,然后根据输入显示一条消息。有效输入(1-10之间的整数)将显示“输入已记录”(此操作正常)消息,任何其他输入(即非整数值、超出范围的整数或文本)应显示“无效输入,请重试”,然后提示用户再次输入。 这就是目前的功能: n = 0; while n == 0 userInput = input('Input an integer from 1 - 10\n'); switch userInput case {1

我正在MatLab中创建一个函数,提示用户输入,然后根据输入显示一条消息。有效输入(1-10之间的整数)将显示“输入已记录”(此操作正常)消息,任何其他输入(即非整数值、超出范围的整数或文本)应显示“无效输入,请重试”,然后提示用户再次输入。 这就是目前的功能:

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
此时,范围内的整数输入触发确认消息,并在循环期间中断
,任何其他数字输入触发我的“无效输入”消息并再次循环,但是,文本输入(例如“五”)会给我一条MatLab错误消息(包括控制台窗口输出的图像)。如何让switch语句也接受文本输入,以避免在用户键入文本时中断代码


显然,我目前正在为此使用
开关
,但我相信如果使用
if,elseif
语句,可能会有更好的解决方案-我愿意接受任何能够完成任务的解决方案

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

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
n=0;
而n==0
userInput=input('输入一个1-10\n','s'之间的整数);%读取输入并将其作为MATLAB字符串返回
userInput=str2double(userInput);
如果(~isnan(userInput)&&&…%转换没有失败,并且
mod(userInput,1)==0&&…%Input是一个整数和

userInput>=1&&userInput应该
five
是有效的输入吗?像
“five”
'five'
这样的输入不会返回任何错误,但是如果您的工作区中没有名为
five
的变量,则
five
将返回错误。@SardarUsama除非您告诉MATLAB将输入作为字符串读取
输入('Input an integer from 1-10\n','s');
。但是首先,如果只允许
5
这样的数字作为输入,或者甚至
5
,Robert应该回答您的问题。嘿,伙计们,除了1到10之间的整数之外,其他任何数字都不应该是有效的输入。它们应该只有整数形式(而不是文本)才有效,所以“5”etc不应该是有效的输入。我可以尝试按照@SardarUsama的说法将输入作为字符串接受,然后使用
str2num
将其转换为int(因为我需要使用此值来选择数组元素)?我编辑了函数,将输入作为字符串接受,然后使用
str2num
将其转换为int。这使各种消息按需要显示,并确保程序只接受我想要的输入。谢谢大家的帮助