【问题标题】:Function in matlab guide to check for invalid valuesmatlab 指南中用于检查无效值的函数
【发布时间】:2018-05-22 08:33:19
【问题描述】:

我正在为我的 Matlab 指南程序编写一个函数。我想在从 0 到 1 的指南中应用 3 个文本框的限制,它应该只是数字。 (如果用户输入的值无效,则应生成错误框)。问题是我想为此编写一个函数,而不是在每个文本框的回调中编写限制代码。用户也不必一次输入所有值,而是当用户输入三个值中的任何一个并生成反馈时,该函数应该运行。我写的功能如下,但它不起作用。 (没有必要将所有三个输入都提供给一个函数,这就是我在输入之间使用 || 的原因)

function CheckMe(maxMBT || minMBT || mainMBT)

 max_MBT= str2double(get(hObject, 'String'));

if isnan(maxMBT)||maxMBT < 0|| maxMBT> 1

  errordlg('Invalid max value for MBT. Please enter values between 0 to 1');
set(max_MBT, 'String', 0);

if isnan(minMBT)||minMBT < 0|| minMBT> 1
    set(min_MBT, 'String', 0);
    errordlg('Invalid min value for MBT. Please enter values between 0 to 1');

if isnan(mainMBT)||mainMBT < 0 || mainMBT >1
    set(edtMBT, 'String', 0);
    errordlg('Invalid value of MBT. Enter values between 0 to 1');

end
end
 end

【问题讨论】:

  • 你不能定义这样的函数。语法是function [out_args = ] &lt;name&gt;(arg1 [, arg2 [...]]),方括号之间的位是可选的。您要做的是定义一个执行检查的函数,并从三个回调函数中的每一个调用该函数。

标签: matlab matlab-guide


【解决方案1】:

您的语法错误,可选参数未通过|| 分隔传递。相反,我建议使用 2 个输入:

  1. 输入要检查的值
  2. 输入这是什么“类型”值,取决于触发的回调。

函数看起来像这样:

function valid = CheckMe( userInput, boxType )
% This checks for valid inputs between 0 and 1.
% USERINPUT should be a string from the input text box
% BOXTYPE should be a string specified by the callback, to identify the box

    % Do the check on the userInput value
    userInput = str2double( userInput );
    if isnan( userInput ) || userInput < 0 || userInput > 1
        % boxType specific error message
        errordlg(['Invalid value for ' boxType '. Please enter values between 0 to 1']);
        % Output flag
        valid = false;
    else
        valid = true;
    end           

end

这个函数返回一个布尔变量valid,你可以像这样在你的回调函数中使用它:

validatedInput = CheckMe( '0.5', 'TestBox' ); % Using the function to check input
if ~validatedInput
    % Input wasn't valid!
    myTextBox.String = '0';
end

【讨论】:

  • 请 Wolfie 帮我解决这个问题,因为我是初学者
  • 我通过留下几乎可以直接在项目中使用的代码和 cmets 的代码来帮助您...您还想要什么?查看您删除的应该是问题编辑的答案,错误很清楚 - MBT 应该是什么?
  • 它应该是字符串。是的,你真的解释得很好。我试过这样做,但它给出了错误。这个合成器好吗? boxType = set (handles.boxType, 'String', MBT)?
  • 不,您尝试将boxType 设置为等于set 命令的输出,但set 命令没有输出...您要做什么就行了?我怀疑你只是想要boxType = get( handles.MyTextBox, 'String' ) 这样的东西,但是我不知道handles 是什么。
  • 如你所说“BOXTYPE应该是回调指定的字符串,用来识别盒子”。我只是想将 MBT 保存为字符串,以便可以将其传递给您提供的函数。那我应该写什么呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多