Matlab Tutorial 3: Strings in Matlab


The concept of variables is fundamental in all programming. In Matlab you introduce variables and assign values to them all by yourself. When you assign a value to a variable its previously assigned value will be overwritten. You can at any time find out the actual value of a variable simply by writing the variable name in the command window (without ;).

The class is decided by the assigned value.

>> a=1; % the class is double and the storage size is 8 bytes.

Open and check workspace.

In this laboratory we will investigate strings and conversions of strings among other things. A string is stored as a row vector, so that every element represents a character. Each character is accessible by the name of the vector and its indice.

Exercise 1: Assigning a variable to a string of characters

>> words='This is a string'

Press on enter to see the content of the variable words. Words has the size 1×16 elements. The class is char (character) and storage size 32 bytes.

>> words(2) % gives the second element in the variable words.
ans = h
>> words(2)='t' % replaces the second element in the vector with t.

Sooner or later we need some form of interactivity. For instance to get input from the user. To prompt the user for an input:

Pages: 1 2 3 4 5

  1. Khashabi — May 19, 2010 @ 6:23 pm

    great !
    go on …

  2. Khashabi — May 19, 2010 @ 7:20 pm

    seems missing a ‘\’ before ‘n’ (new line escape character)
    Line: x= input(‘Give me a name !: n’,’s’); % skips a row

  3. saravanan — November 21, 2011 @ 9:52 am

    You are saying it is possible to change a letter by assigning with new string. Is it possible in structures, for example,

    s.text = ‘TITLE=”PhotoStudio Exported Data”‘
    [1×98 char]
    ‘ZONE T=”PhotoStudio Data” K = 147 F=PAINT’

    OLD STRING
    s.text(3) = ‘ZONE T=”PhotoStudio Data” K = 169 F=PAINT’
    For REPLACING THE STRING, suppose if I assign
    s.text(3) = ‘ZONE T=”PhotoStudio Data” K = 13 L =13 F=PAINT’
    it is not assigning so and what is the problem in it?