【问题标题】:Matlab: If condition working on empty matrices, not working properlyMatlab:如果条件在空矩阵上工作,则无法正常工作
【发布时间】:2013-08-20 21:37:53
【问题描述】:

if 条件语句中的我的变量及其值

leftoverROI1s{1}= [11 15];

missinglabelsinimage{1} 是一个空矩阵。

只有当if 语句中的两个条件都为真时,我才想执行for 循环,即:

if ~isempty(leftoverROI1s{1}) && ~isempty(missinglabelsinimage{1})

    for % loop for each element in non-empty `missinglabelsinimage` structure array.
        % Add a scalar to each element of non-empty `missinglabelsinimage` structure array
        ...
    end % end for loop

end % end if

我的程序控件将进入for 循环(我希望,如果有一个空的missinglabelsinimage{1}) 并且控件正在处理missinglabelsinimage{1}(空矩阵),这显然会给我一个错误因为我正在尝试向我的“非空”missinglabelsinimage{1} 添加一个标量。

我无法理解我的if 条件中的错误。任何帮助将不胜感激。

PS:我检查了上面的变量

~isempty(missinglabelsinimage{1})
ans =    
     0

~isempty(leftoverROI1s{1})
ans = 
     1

missinglabelsinimage{1}
ans =
   Empty matrix: 1-by-0

【问题讨论】:

  • 我不明白你在问什么。如果missinglabelsinimage{1} 为空,而您说它是空的,那么您的if 语句将阻止for 循环执行,这似乎正是您想要的。
  • 报告完整的错误信息和一个可重现的例子。
  • 编写一个重现问题的函数(不是脚本)。

标签: matlab if-statement


【解决方案1】:

我怀疑您未显示的代码中某处存在拼写错误。将您的示例简化为最基本的形式(尝试查找错误总是一个好主意):

a = [];
b = [1 2 3];
display(~isempty(a))
display(~isempty(b))

if ~isempty(a) && ~isempty(b) 
    disp('we passed the if')
else
    disp('we are in the else')
end

输出结果

ans =
     0
ans =
     1
we are in the else

正如您所料。如果您得到不同的东西,那么您使用的代码不是您正在显示的代码......某处是否有类似(错误输入)的变量?尝试执行clear all,然后运行一个重现您的问题的最小示例。

【讨论】:

    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    相关资源
    最近更新 更多