如何在MATLAB中使用if变量的条件?

时间:2017-07-25 04:44:07

标签: matlab variables if-statement

嗨,我是MATLAB的新手。

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

问题是,当我使用条件时,该变量没有任何问题。以下给出部分代码 -

if predictLabels == 1
    imshow(img);
end

以上代码无效。没有错误显示,甚至编译器也没有输入if语句。我认为这种条件检查有一个功能。

1 个答案:

答案 0 :(得分:2)

问题是您的变量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