Sunday, January 3, 2010

Data Type: Strings

Welcome back folks,
Lets continue our discussion on data types in matlab,
Lets look at strings and characters in this tutorial.


One of the most important thing to remember here is that there is 
essentially no difference between string and char data type in matlab,
string is interpreted as character array in matlab. Also matlab gets rid of '\0' terminator for you. This makes working with strings easier in matlab.


>> a='m';
>> b='matlab-nojvm';
>> whos
  Name      Size                    Bytes  Class

  a         1x1                         2  char array
  b         1x12                       24  char array

Grand total is 13 elements using 26 bytes

>> a

a =

m

>> b

b =

matlab-nojvm





Above example should be self explainatory. I dont think we need to go into any further discussions about char and string data types details. (like internationalization and unicode etc. for a very basic reason that I dont know about them ;) )


We will now see how to use strings and different functions associated with strings.


Here is an important point I want to tell you about strings in matlab.
     You "CANNOT" create array of strings having dissimilar lengths. For one to create string array, you have to have strings of equal length.  There is a workaround though. You can either pad spaces to your strings or use special data type called cell arrays which I will describe later.


You can use length() function to check the length of the string.


Many times, you will find need to concatenate strings. This can be done by
strcat() function. See below for an example.

>> a =  'hi';
>> b =  'this';
>> c =  'is number';

>> d = 1;
>> e =  strcat(a,' ',b,' ',c,' ',num2str(d));

>> e

e =

hithisis number1


 
Here I used strcat with spaces in between to create a sentence. See the problem? All spaces are gone..! Well, that is strcat for you.


num2str is just a function used to convert number to string. 

Lets try to do it the other way,

>> sprintf('%s %s %s %d',a,b,c,d)

ans =

hi this is number 1
















This time it works just fine. Here for converting number to string we used %d

instead of %s and then using num2str.

There are other formatting options for converting numbers to string similar to those used in C/C++. You can refer to them in the manual.


Converting string numbers to actual numbers is easy as well,


>> a = '23.23';
>> str2num(a)

ans =

   23.2300



In case, your string has some leading or training spaces, you can trim it by
using strtrim() function. There are some other functions available to do
this kind of job, details of which should be available in the manual.
 This is enough information to get you going with matlab strings. 
See you in the next blog.

~Omkar 






No comments:

Post a Comment