【问题标题】:How to use if condition on a variable in MATLAB?如何在 MATLAB 中对变量使用 if 条件?
【发布时间】:2017-07-25 13:01:36
【问题描述】:

您好,我是 MATLAB 的新手。

我有一个名为 predictLabels 的变量,它的值是 1、2、3、4。对于每个图像,predictLabels 的值都会发生变化。在工作区中,它显示为 predictLabels = '1' etc

问题是,当我对该变量使用 if 条件时,什么也没有发生。下面给出的部分代码-

if predictLabels == 1
    imshow(img);
end

上面的代码不起作用。没有错误显示,即使编译器也没有进入 if 语句。我认为这种条件检查有一个功能。

【问题讨论】:

    标签: matlab variables if-statement


    【解决方案1】:

    问题是您的变量predictLabels 不包含数值。相反,它似乎是 character array ('1') 或 cell array of characters ({'1'})。我猜是后者,这就是为什么它显示为... = '1' 而不是... = 1。无论是哪一个,您都应该在条件检查中使用strcmp 而不是==

    if strcmp(predictLabels, '1')
      imshow(img);
    end
    

    如果您想检查变量的数据类型,可以使用class 函数:

    >> predictLabels = '1';
    >> class(predictLabels)
    
    ans =
    char
    

    或者您可以使用whos 来检查整个工作区的数据:

    >> whos
      Name               Size            Bytes  Class    Attributes
    
      predictLabels      1x1                 2  char
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 1970-01-01
      • 2021-02-11
      • 2016-03-08
      • 2018-06-16
      • 1970-01-01
      • 2022-07-08
      • 2014-06-30
      • 2021-03-23
      相关资源
      最近更新 更多