# Logical Conditions and Matrices

Logical Conditions and Matrices Matlab has an interesting way of using logic to choosing elements of matrices. If I have a matrix

a = [ 1 2 3 4 5 6]

and I refer to a(a>3) I will get only the elements of a where a is greater than 3. You can combine these logical statements. Typing "help ops" will list all of the logical functions and operators you can use for this.

I can also create a second matrix the same size as a: b = [7 8 9 10 11 12]

and then referring to b(a<3) will give the elements of b which correspond to where a is less than 3 (that is, [7 8]).

The reason this works is because matlab logical functions are designed to return a matrix or vector of 1's and zeros. If I just typed

>> a>3

I would get [0 0 0 1 1 1] as a result. The first 3 elements are zero, because those elements are not greater than 3 (F), and the last are 1 because those elements are greater than 3 (T). Then, matlab can accept matrices like this as a way of specifying indexes for another matrix of the same size. If I just typed

>> a([0 0 1 0 0 1]),

I would get [3 6] as a result because those are the elements where 1's appear in the vector I gave as my "index" vector.

This logical indexing capability allows you to do a lot of efficient things with large matrices because you very rarely have to loop through a whole matrix in order to get only specific parts of it. Example: You have a matrix called volt with 50,000 values of voltages over time, and a corresponding matrix called t. To find the mean voltage between time 20 and time 30, you can use

>>mean(volt(t>20 & t<30))

to get the result.