如果向量只包含零,如何检查MATLAB?

时间:2010-05-20 12:42:25

标签: matlab

检查向量是否仅包含零的“MATLAB方式”是什么,以便将其评估为标量而不是向量。如果我运行此代码:

vector = zeros(1,10)

%the "1" represents a function that returns a scalar
if 1 && vector == 0   %this comparision won't work
    'success'
end

我收到错误:

  

???操作数到||和&&   运营商必须可转换为   逻辑标量值。

5 个答案:

答案 0 :(得分:22)

使用all

vector = zeros(1,10)
if 1 && all(vector == 0)   %this comparision will work
    'success'
end

答案 1 :(得分:14)

由于零的处理方式与false相同,因此您无需使用vector == 0,因为ptomato建议。 ~any(vector)是“MATLAB方式”,仅检查零值。

if 1 && ~any(vector)   
    'success'
end

将问题扩展到数组,您必须使用

array = zeros(5);
if 1 && ~any(array(:))
    'success'
end

答案 2 :(得分:4)

有点晚了,但nnzNumber of Non-Zeros)怎么样?

if 1 && nnz(vector)==0
    'success'
end

答案 3 :(得分:1)

您可以使用以下内容轻松查明vector中的任何条目和多少条目是否包含非零元素:

vector = zeros(1, 10); 
nrNonZero = sum(vector~=0)

vector~=0返回与vector相同维度的数组,其中包含0和1,表示给定语句的true和false。变量nrNonZero则包含vector中的非零元素数。

因此,您的代码将是

if (sum(vector~=0) == 0)
    'success'
end

答案 4 :(得分:0)

你也可以这样做:

if(boolFunCall() & ~vector)
    disp('True');  
else
    disp('False');
end

正如Doresoom所述,您的问题在于使用&&代替&。此外,~反转所有的1和0,从而将零向量转换为1的向量:

test = [0 0 0 0 0 0];
~test
ans =

     1     1     1     1     1     1     1
test = [1 0 0 1 0 1 0 0 0];
~test
ans =

     0     1     1     0     1     0     1     1     1