Thursday, December 31, 2009

Data Types: Numeric Data Types

Moving on,
in this blog post, we will look at most commonly used
data types of matlab, integers and double precision numbers.


I have already told you that double is a basic data type of
matlab. So whatever you do in matlab, if you dont provide the
data type for it, matlab will assume the basic data type of double.
for that variable.


I will briefly introduce you to these data types for I sincerely feel that
you can learn more about them once you start using them and ofcourse,
this blog is no way a substitute to the matlab user manual, which
you should refer to time and again.


So these data types are
Integers, Single Precision Numbers, Double Precision Numbers 
and Complex numbers too.


For most of your operations you dont really have to worry about them,
You will really need to know about them once you start working with
conversions between one another and some functions which may specify
input in a prescribed format.


For integers int8,32,64 there are corresponding unsigned versions available.


Conversions from one format to another:

These data types can be converted from one another just by typecasting.
i.e to convert from 
int8 to int64 all you have to do is,
a  =int8(10);
b  =int64(a);
and thats it, you are done.


While converting from floats to integers, there are several options available.
such are popular ceil, floor, round as well as direct conversion by typecasting. (int64.. etc).


Interesting example I found on matlab manual website was to convert 
string to corresponding ascii characters..!


Writing this blog is really useful..!:) I get to know many new functions as well.


Ok,coming back,

str = 'Hello World';

int8(str)
ans =
   72  101  108  108  111   32   87  111  114  108  100

Heres what happens if you convert string to integers.


Images are typically read in int8 arrays. So while storing them back,
its great if you can convert them back to int8.
While converting though or while working with various integer types,
you have to take care not to exceed max limit of data type you have
selected.


Matlab comes with some warning messages related to these integer types.
You can toggle them with
intwarning('on'); and intwarning('off');
 
These come in very handy if you are much into data conversion,
If you are not really bothered about memory, you may want to work with the highest capacity data type possible
Please have a look at intmax function
 
I know that this blog post was bit a reading material than practical examples.
But really going deep inside into every data type is beyond scope of this writing.

Though in matlab you dont have to worry about data types, be extremely 
careful about them and especially their ranges. The can cause disasters in
a great code..!

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


Saturday, December 26, 2009

2) Data Types

Hi,
In the last post, we looked at how to start matlab and did our first program in matlab.

Now that we can start and use matlab, lets start with first of our topics.
"Data Types".

        Please however note that this is just a compilation of few of the functionalities that matlab possesses. More details about capabilities of Matlab can be found at the user manual.  
       Starting on the data types, actually one doesnt need to worry too much about data types in matlab.You dont have to specify data types explicitely for most of your work in matlab.
But, this is not similar to any scripting langauge where you can use same variable interchangeably across program without bothering about the data type. In matlab, you do need to worry about data types, its just that for most of the times you dont have to explicitely set them as we do in C or C++.

         Following figure gives Idea about how matlabs data types are organised.
This figure has been taken from the official user manual of Matlab.



  So as shown by this figure, basic data types in matlab can primarily be divided 
5 categories or classes.
  1. Boolean
  2. Numeric
  3. Text
  4. Function Handle
  5. Heterogeneous Container.
          There is one more data type Map which is essentially a hashtable. We will look at Function Handles and the maps later in advance topics. For now lets focus on the 4 basic types.
But before we do that, lets have a look at one very useful command in matlab whos.
           This command displays all variables present in the workspace in current scope. With listing all the variables, it also lists there data type as well. Here is an example.

>> a = rand(3,4);
>> b = uint8(34);
>> c= 300.234234;
>> whos
  Name      Size                    Bytes  Class

  a         3x4                        96  double array
  b         1x1                         1  uint8 array
  c         1x1                         8  double array

Grand total is 14 elements using 105 bytes


 
              See the different data types listed in the end of each line.

Remember that default data type of matlab is double. So if you do not specify the data type, it will be treated as double or double array to be precise. Lets not worry about this double array too much at this point or in fact anypoint later as well. Here is an example of default assignment.
>> b = 90
b =
    90

>> whos
  Name      Size                    Bytes  Class

  b         1x1                         8  double array

Grand total is 1 element using 8 bytes


              Even when we assign a pure integer value to b, default of double has been assigned.
While this doesnot affect operations in most of the cases, we have to be careful sometimes 
while writing array as an image where integers are required. Also, note that after I assigned 90 to b there is one more line printed there right after I hit enter.This is because I didnot give a semicolon after the statement. If you dont give a semicolon after your statement, final variable getting modified by that statement will be printed on the screen.While this is a very useful functionality at debug time, can be extremely time consuming if you dont give a semicolon for a statement in the for,while loops where matlab has to print the values on the screen every time statement gets executed.
             We will look at two more commands here before we proceed with data types. clc is a command to clear contents of the screen just like familiar "clear" command on terminal. Another command is clear. This is a command used to clear contents of the memory. Be extremely careful while using this command. 

>> a = rand(3,4);
>> v = 23;      
>> p = int32(2321312);
>> whos
  Name      Size                    Bytes  Class

  a         3x4                        96  double array
  p         1x1                         4  int32 array
  v         1x1                         8  double array

Grand total is 14 elements using 108 bytes



Now see what happens after the clear command.



>> clear
>> whos
>>




All variables are gone....!!! and gone permanently. So be extremely careful while using this command.
This command can also be used selectively. You can specify which variable you want to erase.

>> a = rand(3,4);    
>> v = 23;           
>> p = int32(2321312);

>> whos
  Name      Size                    Bytes  Class

  a         3x4                        96  double array
  p         1x1                         4  int32 array
  v         1x1                         8  double array

Grand total is 14 elements using 108 bytes

>> clear a p;        




>> whos
  Name      Size                    Bytes  Class

  v         1x1                         8  double array



See that only variables a and p were cleared from the memory.
This use comes in handy when you have to load a file into the memory and dont want to use all of its contents. You can remove them from the memory.


Now that we know these basic commands, in coming posts, lets start looking at individual data types one by one.


~Omkar



Friday, December 25, 2009

1) Getting Started


Hey There,
Welcome to this first blog on Matlab in Linux series.
Well, as I wrote in the introduction that, I will be assuming basic familiarity with linux systems and bash shell particularly.


      If you have basic knowledge of matlab, that would be an added advantage here.
Goal of this series of blogs is to get people going on matlab linux version, which seems to be a popular choice amongst many image processing labs around the world and getting a display there may not be possible, all you have is a "terminal".
Besides this, there is one more important point that I want to you to understand here. World of machine language programs is too different from usual programs. These programs take hours, days in cases to finish. It makes it extremely important to make use of linux functionalities to cope up with these kind of problems.
So, getting back on track, I am assuming that you have some version of matlab installed on your machine. Hopefully (2008/2009). Use any linux distro doesnt matter really.
Check if you can start normal matlab by typing,
matlab on your terminal.
This should give you the old familiar matlab window on your desktop. We however are going to use command line version. Hence the command in our case would be
matlab -nojvm
This command should give you the matlab prompt. as follows

[omkar@localhost ~]$ matlab -nojvm


< M A T L A B >
Copyright 1984-2004 The MathWorks, Inc.
Version 7.0.0.19901 (R14)
May 06, 2004


To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
>>


This is that famous matlab prompt.
Now that we have prompt, The second most important thing to have is an editor.
I will be using vim editor. You can use any one of your choice.

So open another terminal window.
Go to the directory where you want your first program to be,
Open the edior and write the following line into it,


display('This is my first Matlab program');
display ('Halo World');


Save the file as first.m As many of you might know, ".m" is a file extension of matlab
program files just like .c is for c programs.

Now go back to your terminal window where matlab is opened,
Make sure that you are working in the same directory where you stored your program.
You can check your current working directory by command pwd.
It will be the directory from where you have started matlab.
So in my case it looks like this.

>> pwd

ans =

/home/omkar

You can change the directory by command cd destination_path
Matlab should provide you with autocomplete with TAB key as you type the path, just as
your terminal does.

So once you are there the directory you created your program in,
check if your program is the there by ls '*.m' command.

>> ls '*.m'
first.m

Now everything is done, matlab has been started, we wrote our first matlab program,
we are there in the directory that we stored it in,
Only thing remaining now is to execute it,

So,
Just type the name of the file on the terminal, excluding the .m
>> first
This is my first Matlab program
Halo World

Thats it, we did it, the first of our matlab command line program. See.. The world here is not
That difficult as it may seem.
See you in my next blog then,where we will start looking at things in more details.
Do let me know your views about the blog.

~Omkar