Thursday, December 31, 2009

Data Type: Boolean

Lets start our discussions about matlab data types with the first data type,
"boolean".

This is one of the basic yet important data type in matlab.


Let me start with example straight away.
Lets consider any random array a.



>> a = rand(1,5)

a =

    0.7621    0.4565    0.0185    0.8214    0.4447



How can you tell me how many of these elements are greater than five?


The typical algorithm would be,


counter = 0;

for(i=1:count(a))
    if(a(i) >0.5)
        counter++
    end
end



And your counter will have value 2 at the end of the loop for array in above example.


Lets consider matlab way of doing it,

>> sum(a(:)>0.5)

ans =

     2


Thats it, just a single line.. This is a beauty of matlab.
Now going into bit details,lets see what happened here,
This statement can be broken into two shorter statements really,

a(:)>0.5 and sum.

a(:)>0.5 returns us an array of same size that of a.
Only the data type is different "Logical" .











>> a(:)>0.5

ans =

     1
     0
     0
     1
     0

>> whos
  Name      Size                    Bytes  Class

  a         1x5                        40  double array
  ans       5x1                         5  logical array


 As you can see here, the logical array has only 2 values.. quite obviously.

It has value 1 at indices where the original array had values greater than 0.5


There are several functions which mainly do comparison operation. These
functions typically return value of this data type.


Let see one more example here.. not exactly related to the boolean data type,
but worth looking at this juncture.


What if I asked you to change every value of the array above 0.5 to 0.35?
How do you do this in matlab?
Well its simple two statement procedure.

>> index = find(a(:)>0.5)

index =

     1
     4

>> a(index) = 0.35

a =

    0.3500    0.4565    0.0185    0.3500    0.4447



Find function is used here, which returns exact indices of the array elements satisfying the requested condition. Remember earlier we just got the logical array of 1s and 0 at positions where condition was satisfied and not satisfied 
respectively. Find is just a step ahead on it.


Then I just use the index array to set values to 0.35.


Simple ... isnt it?


Well here is a take home message...!
Matlab provides several such functionalities where you can get away with 
statement or two when you would have written atleast few statements otherwise.
Not only this saves your time in coding, but these inbuilt functions are
electric fast as compared to your own for loop. 
So..! There is double benefit here...


Thats it folks for this blog..!
See you in next blog..!

~Omkar


No comments:

Post a Comment