Logical operations and logical indexing in Matlab

Nerd of all countries, standout! Source : Image

Nerd of all countries, stand up! Source : Image

In this post, we talk about logical operations but also how to use your Matlab skills to analyze your shopping expenses (Yes, we are all absolute nerds and love it).

You will learn how to use logical operations to search large data matrix very quickly. If you have never used logical operators in Matlab, this is a MUST-READ!

All along this post, we will assume you already understand what boolearn operations are. If not, I urge you to revise your basic boolean algebra (especially the AND, OR and NOT gates).

Boolean operations are very core components of computer technologies. The reason for that lies in how transistors works: by combining just a few transistors, you can easily create all possible boolean operations. As any other programming language, Matlab supports basic logical operations. More over, as you will see, logical operations can elegantly be mixed with matrix operations. As such logical operations are important components of the language.

Here’s a simple summary of syntax and input/output types for the 3 most important logical operators : the AND, OR and NOT.

Operation Type of input Type of output  Syntax for element-wise operators (A, B, C can be matrices, vectors or scalars)
AND Logical/double Logical C = A & B
OR Logical/double Logical C= A | B
NOT Logical/double Logical C= ~ A

Notice something unusual compared to what you know from basic arithmetic?

  • Firstly, your inputs need not be just 1 and 0 or True and False. These operators can work on floating point numbers or integers. Non-zero inputs (positive or negative) is considered as a logical 1 and only 0 inputs are considered logical 0.
  • Please note how you DON’T need the famous ‘.’ to convert a ‘&’ into an element-wise operation (i.e. ‘.&’ ).

So let’s explore where and how these functions can come in handy.

We will work with a nice example contemporary to this post : Black Friday (for the Non-american in the audience, Black friday is a day the entire US population goes shopping to look for discounted items) . Suppose that lately you have been a bit of a shopaholic, thanks to online shopping. You need someone to talk you out of it every time you are tempted to spend. And you are a nerd, so you would like that someone to be Matlab rather than your judgmental friends.

So let’s say that now you have vowed to get your shopping habits in order and you are keeping a monthly shopping diary in an Excel file and you analyze it at the end of each month, again using Matlab (yeah, you really are a nerd). It could look something like this.

An example shopping list in Excel.

An example shopping list in Excel.

You can read your monthly expenses from the excel file in an array in MATLAB using xlsread.


Now you have your expenses in a vector and you would like to know :

  • how many items you bought or rented that have cost you more than $100.
  • how many were less than $50.
  • how many were between $100 and $500.
  • etc…

Let’s first find out on how many items you spent between $100 and $300 and what these amounts were.

Since you have a matrix Nov28Expenses, it is very easy to check, using the boolean operators AND (or &) if one particular element is between 100 and 300 dollars :

Nov28Expenses(1)>=100 & Nov28Expenses(1)<=300

Now operating this on the entire matrix is straight-forward using a for loop.

for i=1:length(Nov28Expenses)

   if Nov28Expenses(i)>=100 & Nov28Expenses(i)<=300
      Costs100to300=[Costs100to300 Nov28Expenses(i)]; % concatenating
display(['You spent between $100 to $300 on ' num2str(length(Costs100to300)) ' items.' 'Individual costs are ' num2str(Costs100to300) ' dollars.'])

In the above program, elements of the vector are individually dealt with in successive iterations and the result is stored in Costs100to300.

The above code can be done much more elegantly using the find function.

Try running this command instead of the for loop.

Costs100to300=Nov28Expenses(find(Nov28Expenses>=100 & Nov28Expenses<=300));

Let’s analyze what is going on here.

  • Nov28Expenses>=100 & Nov28Expenses<=300 gives a matrix with logical entries.

>> Nov28Expenses

Nov28Expenses =

200   100   60   500   30   20   60   150   210

>>Nov28Expenses>=100 & Nov28Expenses<=300

ans =

1     1     0     0     0     0     0     1     1

  • find function returns the indices of all non-zero entries

>> find(Nov28Expenses>=100 & Nov28Expenses<=300)

ans =

1     2     8     9

  • Finally Nov28Expenses(.) selects the elements of Nov28Expenses indicated by the indices [1 2 8 9]

All of this has been done with just one command !

Now Matlab offers a way to do all of the above even more elegantly. It’s called logical indexing.

Try running this command now. It also gives exactly the same result :

Costs100to300=Nov28Expenses(Nov28Expenses>=100 & Nov28Expenses<=300);

Notice that in this case, the find function is not needed. MATLAB automatically selects those indices at which there is a logical 1 and leave out those where there is a logical 0.

You can try more complex operation with logical indexing.

Suppose you would like to know how much you can save by cutting down the price of all items by 10%. However you know you cannot cut your $500 rent, so you have to do something like that :



As you progress in your mastery of the language, you will realize the importance of this very simple post (after the post on code poetry and the one on the profiler, of course… 😉 )

A variant of these boolean operators is also available in Matlab. It’s called the short-circuit operator. It’s meant to work only with single-element booleans. I invite you to consult my post on the matter.

This entry was posted in Beginners. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *