1

I am using Matlab.

I compare a zero array A with some other arrays (e.g. [1 1 0 0])

I write the following code:

A=[0 0 0 0];

if (A~=[1 1 0 0] & A~=[1 0 1 0] & A~=[1 1 0 1])
    x=1;
else
    x=0;
end

I expected to see that x=1 but the answer i get is x=0

what do i wrong ?

1
  • why do you expect to see x=1? Commented Mar 27, 2014 at 14:07

3 Answers 3

1

~= and & are element wise operators, so the expression

A~=[1 1 0 0] & A~=[1 0 1 0] & A~=[1 1 0 1]

where A = [0 0 0 0] produces the vector output:

[1 0 0 0]

An if statement evaluated on a vector does an implicit all, which in that case evaluates to false.

It's not exactly clear what you want, but if you want to make sure the vector A is not equal to any of [1 1 0 0], [1 0 1 0] or [1 1 0 1] then you need to do this:

x = ~isequal(A, [1 1 0 0]) && ~isequal(A, [1 0 1 0]) && ~isequal(A, [1 1 0 1])
Sign up to request clarification or add additional context in comments.

Comments

1

The matlab equality operators compares array element-wise and returns true/false (logical 1/0) for each element. So when you have A = [1 1 0 0], B = [1 0 1 0] and you check for A == B, you don't get 'false' but instead you get [1 0 0 1].

If you want to check if the whole vectors A and B are equal you need to check if the condition all(A==B)is true or not

Comments

0

I think you are looking to find exact match, so for that you may use this -

%%// If *ANY* of the element-wise comparisons are not-true, give me 1,
%%// otherwise give me 0. Thus, in other words, I am looking to find the 
%%// exact match (element-wise) only, otherwise give me 1 as x.
if any(A~=[1 1 0 0] & A~=[1 0 1 0] & A~=[1 1 0 1]) 
    x=1;
else
    x=0;
end

Another way to put it would be -

%%// *ALL* elementwise comparisons must be satisfied, to give x as 0, 
%%// otherwise give x as 1.
if all(A==[1 1 0 0] & A==[1 0 1 0] & A==[1 1 0 1]) 
    x=0;
else
    x=1;
end

Get more info about any and all, that are used here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.