Feed on Posts or Comments

Matlab & Tips and tools Andrew Kun on 15 Oct 2007 09:55 am

Matlab “not equal” function - be careful how you use it!

When using the Matlab “not equal” function (~= or ne) with vectors and matrices, one has to be careful. I found this out the hard way, playing with some m-code for a homework in my Introduction to Neural Networks course. The issue is that the ~= function evaluates matching pairs of vector/matrix elements one at a time and produces a vector/matrix output. For example, you can do this in the Matlab command window:

>> a = [1 1];
>> b = [1 2];
>> a~=b

ans =

0 1

What’s to be careful about? Well, I wanted to use ~= in an if statement. To do this, type the following in the Matlab command window:

>> if max(a~=b) > 0; c = 1; else c = 0; end
>> c

c =

1

What if you just evaluate a~=b? For the example above:

>> if a~=b; c = 1; else c = 0; end
>> c

c =

0

Not what you expected, right? It took me a while to catch this. Of course, I could have read Bruce Driver’s Matlab primer (scroll down to the end of Section 6). From his page I also learned that the following will work (note that each corresponding element of a and b is different):

>> a = [1 1];
>> b = [2 2];
>> if a~=b; c = 1; else c = 0; end
>> c

c =

1

Bruce also suggests using the “any” Matlab function in the above evaluation as well as just simplifying the whole thing by looking for vectors/matrices that are equal:

>> a = [1 1];
>> b = [1 2];
>> if a==b; c = 0; else c = 1; end
>> c

c =

1

So, be careful, the Matlab ~= function returns a vector/matrix when you compare vectors/matrices.

Andrew Kun

Subscribe to the comments through RSS Feed

Leave a Reply