- Matlab - https://matlab.diyez.net -

Matlab Tutorial 3: Strings in Matlab

The concept of variables is fundamental in all programming. In Matlab [1] 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:

>> x= input('Please give me a name: ','s'); % Matlab expects a 
% number, string or a matrix [2] from the keyboard.
% The second argument says the returned variable
% should be a string.
>> disp('The name is: '), disp(x) % gives text as output and the value of x.

We can also introduce the escape character sequences n for the command input. This can be written as:

>> x= input('Give me a name !: n','s'); % skips a row.
>> disp([x ,' that was a very nice name !']) % displays the name+string.

Read a matrix from the command window and upon return display it. Use input and disp. It is no difference from reading a number.

>> A=input('Give me a matrixn'); disp(A)

We shall now look on another example where we have a interaction with the command window. Now we will use a trigonometric function as a string input. The m-file looks like below:

% The m-file was created by MatlabCorner.com.
% The user can choose between three trigonometric functions and
% have these plotted.
% The command fplot have two input arguments. The first one is a
% string and the second one is a vector that gives the plot interval.
fcn= input('Choose one of the functions: sin, cos or tan: ', 's')
fplot(fcn,[0 40])

We stated earlier that a string of characters is a row vector and this is nothing than a special case of a matrix, so we can create matrices consisting of strings, but note that these strings must have the same lengths. Otherwise each element in the matrix will differ and we can’t perform the basic operations such as addition, subtraction and so on. Now we present some typical names as strings:

>> S1='Jannis   ' % 8 characters, two are blank.
>> S2='John    ' % 8 characters, four are blank.
>> S3='Tatiana ' % 8 characters, one is blank.
>> S4='Jenna   ' % 8 characters, three are blank.
>> A=[S1 S2 S3 S4] % a matrix A, its elements are strings.

It is possible to assemble strings of characters in many different ways, but sometimes you would also like to have numbers inserted in the strings. This can be arranged by using conversions. We can now try the command num2str. The command converts a numerical value to a string.

>> x=num2str(123.4567,3) % converts the number to a string 
% with three characters.
>> u=['The number is ', x, ', who would have guessed !'];
disp(u)

There are lots of conversions in Matlab. In the table below we show some of them:

There are of course many more different conversions, but we will stop there and try a few of them:

>> dec2hex(10)
>> dec2hex(12)

For those of you who are not familiar with hexadecimal numbers: it simply means that the base is 16, and the representation uses the numbers 0,1,2…9, A,B…..F and not 0, 1, 2…..9, 10,11,…15. Also try to go back from a hexadecimal representation to decimal representation. Don’t forget that the argument is a string. What becomes dec2base(4,3)?

>> dec2base(4,3) % converts the number 4 (base 10) to a number with base 3.

There are logical functions for strings and functions to pick substrings. We have functions to add blanks and subtract characters. We can also alter from small to capital letters and vice versa. We can also decide if we have letters in a string. Comparison of strings are also possible and to decide if they are equal and many other things. I choose to exemplify the following:

Introduce a string

>> str1='What’s your name ?' % Put some blanks after the letters.

and yet another string

>> str2='What’s your name ?' % Without any blanks.

Try some of the commands of the previous list. Especially the commands deblank, lower, upper, ischar, isletter and isspace with the argument str1. Try:

>>isletter(str1(3))
>>isletter(str1(4))

Also try to compare strings. What becomes the following:

>> strcmpi(deblank(str1),str2) % deblank(str1), creates a new string.

Finally to examine the last to commands in the table.

>>str3='peter'
>>strfind(str1,str3)
>>findstr(str1,str3)

Exercise 2: Eval function

In the m-file below there is an example of how to use the command eval. The m-file also contains an repetition consisting of a for-loop. It is executed for n=1,2,3 and 4 and then the program is finished. Execute the program to find out how it works.

% The m-file was created by MatlabCorner.com.
% Magic(N) is a N-by-N matrix constructed from the integers
% 1 through N^2 with equal row, diagonal and column sums.
% Produces valid magic squares for all N> 0 except N=2.
for n=1:4
         eval(['M' num2str(n) '=magic(n)'])
end

Please notice that the Matlab command num2str is inside a string vector and evaluated with the Matlab command eval. We have in the two previous Matlab tutorials [3] studied the concept function and used it to solve some simple problems. The function is called with or without several input arguments, but there are of course other possibilities to create functions. We will create an inline function that can be used in a similar way as the traditional function m-file.

g=inline(expr, arg1,arg2) Creates an inline function g from the expression expr that can be called with the variables x and y. Let’s illustrate this with an example:

>> g=inline('3*sin(x)+cos(y)','x','y') % definition of the function.
g =
Inline function:
g(x,y) = 3*sin(x)+cos(y)

Now we can use this function simply by writing :

>>g(pi, 2*pi) % x=pi and y=2*pi
ans=
1.0000

We can also evaluate the function g for different x-y pairs and get the function plotted.

>> x=0:10; y=0:10; % contains all integer values from 0 to 10.
>> g(x,y)% results in a vector with 11 elements.

Exercise 3: Evaluating functions in a loop

Write an m-file that evaluates a function 3*sin(x)+2*cos(x)+tan(x) every tenth degree between 0 and 360. Plot the function versus x with suitable title and labels. Display the calculated values in a matrix according to: function values and x in two columns.

Exercise 4: Matrices including elements from different classes

We have earlier used matrices containing numerical elements or string of characters, but the elements must be of the same class, but matlab also permits other forms of matrices to exist with elements of different classes like cell arrays, but you can not perform the operations like multiplication, subtraction, addition and so on these. But remember that all rows and columns must have the same length as for an ordinary matrix. How how to create a cell array?

>> D=cell(3,4)% gives an empty cell array, with 3 rows and 4 columns.

Assignment can be achieved assigning each and every cell like:

>> D{1,1}=123.23
>> D{1,2}='kalle'
We can of course also make the whole cell array from the beginning.
>> A={'Charles', 'Anderson', 23, 'football';'Gwen','Nolan',34, 'golf'}
A =
'Charles' 'Anderson' [23] 'football'
'Gwen' 'Nolan' [34] 'golf'

Different applicable commands to cell arrays can be found in the table below:

>> cellplot(A)% the result can be seen in figure below
Charles Anderson 23 football
Gwen Nolan 34 golf

matlab-string-array

We will also exemplify how cell2struct can be used. If the concept structure is not known from programming you will also have a possibility later on in the course to get to know the concept. Structure is a variable containing different fields. Think of it as a method of organizing the variable. Each field can be accessed by dot notation.

>> E=cell2struct(A,{'first_name','last_name','age','sport'},2)

% notice that dimension is now 2.
E =
2x1 struct array with fields:
first_name
last_name
age
sport
Display the different fields within the structure:
E(1)
ans =
first_name: 'Charles'
last_name: 'Anderson'
age: 23
sport: 'football'
E(2)
ans=
first_name: 'Gwen'
last_name: 'Nolan'
age: 34
sport: ’golf’