© Irfan Turk 2019
I. TurkPractical MATLABhttps://doi.org/10.1007/978-1-4842-5281-9_1

1. Introduction to MATLAB

Irfan Turk1 
(1)
Nilufer, Bursa, Turkey
 

MATLAB is an abbreviation for the expression Matrix Laboratory. It has been widely used in many kinds of applications and fields of study. MATLAB is a high-level language, the reputation of which has been increasing over time. Since its first use in 1970 by Cleve Moler, a famous mathematician and cofounder of MathWorks, Inc. (the owner of MATLAB), it has shown huge advancement and new tools have been added in the new versions released twice a year.

Due to the fact that it has a remarkable number of toolboxes, MATLAB attracts many users from a variety of different areas ranging from engineering to applied sciences. MATLAB has a large number of built-in functions that make the programmer’s job easier when it comes to solving problems. Although it is used primarily for technical computing and addresses toolbox-oriented jobs, MATLAB carries a very practical and easy programming language aspect, as well. One of the important goals of this book is to emphasize the programming language aspect of this powerful software.

MATLAB possesses tools that satisfy the programmer’s needs in many applications. Even, these days, specific tasks often require specific software. However, MATLAB can suit programmers’ demands in most cases.

The MATLAB prompt displays as a double greater sign (>>) in the command window. Due to the trademark and logo usage guidelines of MathWorks, Inc., the ∎> symbols will be used together throughout this book to represent the MATLAB prompt.

In this chapter, you will learn the necessary concepts of coding of the language when it comes to solving real-life applications.

MATLAB Environment

When you run MATLAB, the programming frame is opened. The cursor awaits in the command window with the prompt > preceding it. If you run the student version, the prompt is EDU>.

Let us explore the console of MATLAB, which has a simple appearance. The default window will look like Figure 1-1.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig1_HTML.jpg
Figure 1-1

MATLAB environment

When you open MATLAB, its interface has the following windows:
  • Command Window: This is the window in which we enter commands.

  • Current Folder: This window shows the directory in which MATLAB operates.

  • Workspace: We can see the program variables in this window.

  • Command History: Here we can monitor the previous commands that we typed in the command window.

  • Editor: We can write code that we want to run as an m-file in this window.

The user might want to close any of these windows to reorganize the interface. You can also customize the appearance interface, such as the way it looks in terms of color, font, and so on. Click ENVIRONMENT and then Preferencesto open the menu shown in Figure 1-2.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig2_HTML.jpg
Figure 1-2

Changing properties

Just by clicking on the items in the left frame shown in Figure 1-2, you can customize these settings based on your preferences.

When working with MATLAB, one of the most useful commands is the help command, which illustrates how a command works and how it is used in MATLAB. Once you type help and press Enter, you can click on any of the underlined subjects on the resulting screen to review them in detail.

If you are new to MATLAB, you can watch some tutorials available through a demo. If you type demo in the command window, you can select from any of the available topics to explore:
>demo
>
By clicking on any topic, you can watch the related tutorials, or see explanations of commands with illustrative examples. Some of the introductory commands used to carry out some basic operations such as closing MATLAB or recording a session from the command window are listed in Table 1-1.
Table 1-1

Some Basic Commands Used in MATLAB

Function

Explanation

Example

help

Returns information about the specified command

>>help clc

demo

Shows the explanation of any subject in MATLAB

>>demo

save

Saves the workspace variables to the named file

>>save my_var

diary on

Starts recording the session

>>diary on

diary off

Stops recording the session and saves it to a diary file

>>diary off

exit

Terminates MATLAB

>>exit

quit

Terminates MATLAB

>>quit

clc

Clears the screen

>>clc

clear

Clears all variables or any specified variable from the workspace

>>clear all

who

Displays all the variables in the workspace

>>who

whos

Displays all the variables in the workspace with sizes and types

>>whos

Throughout the book, examples demonstrate the usage of MATLAB. Each example illustrates an important aspect of a feature of the subject in the relevant chapter.

In MATLAB, you can save your session from start to finish by saving your session with the save function. We can take a look at the following example of this.

Example 1-1. Type disp ('Hello World') at the prompt. Save your session in a file named my_session.

Solution 1-1. The following piece of code can be typed at the prompt.
> diary my_session
> disp('Hello World')
Hello World
> diary off
MATLAB will create a file named my_session in your current directory. If you click on the file, it will be appear in the editor as follows.
disp('Hello World')
Hello World
diary off

In this code, the command disp() displays whatever is typed between the single quotation marks next to it. If the expression to be displayed is a number, then there is no need to include the quotation marks. If the expression is a string or a letter, then we need to include the quotation marks before and after the text along with the disp() function.

Using MATLAB as a Calculator

MATLAB can be used as a calculator, as well. You can find the solution for any complex calculation. In the following example, we can see an illustration of this function.

Example 1-2. Find the result of $$ 5-frac{8}{3}+ coscos left(pi 
ight)-frac{10}{e^2}+sqrt{7} $$.

Solution 1-2. The following code will find the solution.
> 5-8/3+cos(pi)-10/exp(2)+sqrt(7)
ans =
    2.6257
>

As shown in the preceding code, π is represented by word pi in MATLAB. For the Euler’s number e, we need to type exp(2), and sqrt(7) should be used for finding the square root of 7. Because we did not assign a variable to the result, the result is shown as ans and it is printed on the screen, where it stands for answer.

Variables and Expressions

In programming languages such as C, C++, and Java, the type of the variable should be specified before the variable is used. However, in MATLAB, this is not the case. The variables are ready to use by just assigning their values. That makes MATLAB more practical for writing shorter and simpler code more quickly.

Some expressions, such as if, for, or end are reserved for the scripts of the language. These words are called keywords. To see a list of the keywords used in MATLAB, simply type iskeyword at the prompt.

Unlike in Example 1-2, we can assign variable names to the solutions to use them later as well. This is called assigning. By typing the following command at the prompt,
> my_var = 3
my_var =
     3
>

we assign 3 to the variable named my_var. Any defined variable is stored as a double precision type in MATLAB by default, unless otherwise specified. Here, the variable my_var is a 1 x 1 matrix with type double. We examine data types later in this chapter.

To display the defined variables and the information carried by them in the workspace, the function whos can be used.
> whos
  Name        Size            Bytes     Class     Attributes
  my_var      1x1             8         double
>
There are certain rules for assigning a name to a variable. Variable names cannot be selected in a random manner; they must meet the following requirements:
  • They should start with a letter.

  • They can contain numbers and underscores.

  • They can be a maximum of 63 characters long (the namelengthmax command can be used to check this).

  • They should not be a keyword adopted in the MATLAB language.

To avoid confusion, any variable name to be assigned can be checked to see whether it is usable or not at the prompt using the isvarname command.

Another important point that programmers should keep in mind is that MATLAB is a case-sensitive language. In other words, there is a difference between a=5 and A=5 once they are defined in the workspace.

Example 1-3. Check whether it is permissible to use the following names as variable names in MATLAB: Howareyou, hi!, Hola+, Heidi, for, name1, Okay_5

Solution 1-3. We can use the isvarname command to check each of these names. If the result is 1, then it is acceptable to use the name. If the result is 0, the name cannot to be given to a variable. The first two names are checked here as an example:
> isvarname Howareyou
ans =
  logical
   1
> isvarname Hi!
ans =
  logical
   0
>

Here, 0 or 1 values are assigned to the ans variable, the class type of which is logical.

As you can see, whenever new information is entered at the prompt, it is repeated. If you do not want the computer to repeat what you typed at the prompt, you can insert a semicolon at the end of the line before you press Enter.

Example 1-4. In the equation P*V = n*R*T, the variables are given as P=10, n=2, R=7, and T= ½. Find V according to the given formula.

Solution 1-4. We can enter the following in MATLAB for the solution.
> P=10;
> n=2;
> R=7;
> T=1/2;
> V=(n*R*T)/P
V =
    0.7000
>

As we can see, there are semicolons after each line except the last one. Because there is no semicolon to the right of the last line, we can see the result of that line after pressing Enter.

Formats

In MATLAB, there are line spacing formats and various numerical formats. Line spacing formats control the spacing between the lines in showing the results at the command window. Numerical formats shape the representation of the output.

Per the line spacing format, there are two options: compact and loose. The compact option keeps the lines tight and closer, whereas the loose option introduces additional spacing between the lines in the command window.

Example 1-5. Let A=22/7. Show A both in compact format and loose format in the command window.

Solution 1-5. If you type the following in the command window, you will see the variable A in both formats.
> A=22/7;
> format compact
> A
A =
    3.1429
> format loose
> A
A =
    3.1429
>

We use the compact format throughout this book to save space.

As for the numerical formats, more options are available. If the format is not altered, the default, format short, is used. This format yields calcuations to four decimal places by default. Different alternatives are shown in Table 1-2.
Table 1-2

Numerical Format Types

Style

Display

Example

format short

Shows 4 decimal digits (default)

0.3333

format long

Shows 15 decimal digits

0.333333333333333

format shortE

Shows 4 decimal digits in scientific notation

3.3333e-01

format longE

Shows 15 decimal digits in scientific notation

3.333333333333333e-01

format shortG

Same as format short, or format shortE, whichever is more compact

0.33333

format longG

Same as format long, or format longE, whichever is more compact

0.333333333333333

format shortEng

Shows 4 decimal digits in engineering notation

333.3333e-003

format longEng

Shows 12 decimal digits in engineering notation

333.333333333333e-003

format +

Positive/negative/blank

+

format bank

Shows in currency format with 2 digits after decimal points

0.33

format hex

Shows the hexadecimal representation

3fd5555555555555

format rat

Converts the decimal number to a fraction

1/3

Example 1-6. Let A=22/7. Show A in the formats of long scientific notation, short engineering notation, hexadecimal format, and fraction.

Solution 1-6. The commands used in the solution and the corresponding output are shown here.
 > format longE
> A
A =
     3.142857142857143e+00
> format shortEng
> A
A =
     3.1429e+000
> format hex
> A
A =
   4009249249249249
> format rat
> A
A =
      22/7
>

Vectors and Matrices

MATLAB’s foundation is based on matrices. In other words, the basic data type in MATLAB is a matrix. There exist close relations among arrays, vectors, and matrices. In this section, we explore arrays, vectors, matrices, and the colon operator used in MATLAB.

Arrays

An array is a group of objects having the same type, size, and attributes. An array that consists of one element is called a scalar. Arrays can be specified as vectors or matrices. A list of arrays arranged as a column or as a row is a one-dimensional matrix. We can think of a 4 × 5 matrix, having two dimensions as shown in Figure 1-3.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig3_HTML.jpg
Figure 1-3

An array

In Figure 1-3, the cell filled with yellow represents the array that constitutes the second row and the fourth column of the matrix. Therefore, we can think of arrays as elements of matrices.

Vectors

A one-dimensional matrix that represents a row or a column matrix is called a vector. In the example shown here, A is a row vector having four elements and B is a column vector having three elements.
$$ {displaystyle egin{array}{l}mathrm{A}=left[egin{array}{cc}1& 2end{array}kern0.5em 3kern0.5em 4
ight]	o 1;mathrm{x};4;mathrm{array} 4 mathrm{elements},mathbf{row} mathbf{vector}\ {}mathrm{B}=left[egin{array}{c}1\ {}3\ {}5end{array}
ight]kern2.759999em 	o 3;mathrm{x};1;mathrm{array} 3 mathrm{elements},mathbf{column} mathbf{vector}\ {}kern2.52em mathrm{B};(3)=5;kern0.36em mathrm{A}(2)=2;end{array}} $$
To form a row vector, it is sufficient to leave a space between the cells. Also, a comma can be placed between the numbers as shown at the prompt here.
> A=[1,2,3,4]
A =
     1     2     3     4
> A=[1 2 3 4]
A =
     1     2     3     4
>
To create a column vector, we need to insert a semicolon between the numbers at the prompt as shown here.
> B=[1;2;3]
B =
     1
     2
     3
>
Using the size and length commands , you can check the size and length of the vectors A and B just specified.
> size(A)
ans =
     1     3
> size(B)
ans =
     3     1
> length(A)
ans =
     3
> length(B)
ans =
     3
>

linspace Command

The linspace command provides a very convenient way of forming a vector. Any vector can be created using this command when you want to use elements that are equally spaced.

For example, one could create a vector between 1 and 10 having 10 elements by just typing the following command at the prompt:
> Vec=linspace(1,10,10)
Vec =
     1     2     3     4     5     6     7     8     9    10
>
The same vector can be obtained in another way, as shown here:
>Vec=1:1:10
Vec =
     1     2     3     4     5     6     7     8     9    10
>

In this example, the vector starts with 1, and approaches 10 with an increment of 1. That is a very efficient way to create vectors in many problems.

Matrices

An array with more than one dimension is called a matrix. As shown here, A is a 3 × 2 matrix with two dimensions.
$$ mathrm{A}=left[egin{array}{cc}1& 2\ {}egin{array}{l}3\ {}5end{array}& egin{array}{l}4\ {}6end{array}end{array}
ight]kern2.759999em 	o 3;mathrm{x};2;mathrm{matrix} 6 mathrm{elements} $$
A(3,2) =6
Row #     Column #
When creating a matrix in MATLAB, we need to insert semicolons between rows as seen here.
> A=[1 2;3 4;5 6]
A =
     1     2
     3     4
     5     6
>

Special Matrices

There are a number of special matrices in MATLAB that are often used to make programmers’ jobs easier. These matrices can be used instead of needing to create them from scratch, thus saving time in programming. A list of the most useful ones is given in Table 1-3.
Table 1-3

Special Matrix Functions in MATLAB

Function

Explanation

Example

eye

Creates an identity matrix

eye(5)

ones

Creates a matrix where all the elements are ones

ones(5)

zeros

Creates a matrix where all the elements are zeros

zeros(5)

diag

Extracts or displays the diagonal part of a matrix

diag(A)

sparse

Creates a matrix where all the elements are zeros

sparse(5,5)

spdiags

Extracts all diagonals from the matrix

sparse(A)

speye

Creates an identity sparse matrix

speye(5,5)

rand

Creates a randomly generated matrix with values between 0 and 1

rand(5)

magic

Creates magic matrices

magic(3)

One of the special matrices from Table 1-3 is shown here.
> magic(3)
ans =
     8     1     6
     3     5     7
     4     9     2
>

Colon Operator

The colon operator is a very important feature that lets users manipulate matrices and vectors. For vectors, we summarize the operator as shown in Table 1-4.
Table 1-4

Use of the Colon Operator for Vectors

Representation

Description

Example

y=a:b

Starts from a, and goes with an increment of 1, up to b

> y=1:5

y =

1   2   3   4   5

>>

y=a:step:b

Starts from a, and goes with an increment specified by step, up to b

> y=-10:2:3

y =

-10   -8   -6   -4   -2   0   2

>

For matrices, we show its usage with rows and columns in Table 1-5.
Table 1-5

Use of the Colon Operator for Matrices

Representation

Description

Example

A( :,k)

Is the kth column of A

> A=[1 2 3;4 5 6;7 8 9];

> y=A(:,2)

y =

2

5

8

>

A( n, :)

Is the nth row of A

> y2=A(1,:)

y2 =

1     2     3

>

Table 1-6

Some Math Functions

Function

Explanation

exp

Exponential function

log

Natural logarithm function

log10

Common logarithm function in base 10

reallog

Natural logarithm of a real number

sqrt

Square root of a number

nthroot

Real nth root of a real number

Example 1-7. In a function given by y = 3x, obtain the values for the vector x = [0, 0.5, 1, 1.5, 2]. Write a code to obtain the results in MATLAB.

Solution 1-7. We can create vector x, and calculate the values for the function as shown here.
> x=0:0.5:2
x =
         0    0.5000    1.0000    1.5000    2.0000
> y=3.^x
y =
    1.0000    1.7321    3.0000    5.1962    9.0000
>

Example 1-8. In a matrix given by A = [0 − 1 2 4 2 3 9 8 5 ], two vectors, B and C, are defined as the second column, and the second and third elements of the third row of matrix A, respectively. Write code to obtain the vectors B and C.

Solution 1-8. Using the colon operator, we can easily obtain B and C as shown in the following prompt.
> A=[0 -1 2;4 2 3;9 8 5];
> B=A(:,2)
B =
    -1
     2
     8
> C=A(3,2:3)
C =
     8     5
>

Built-in Functions

MATLAB has numerous built-in, ready-to-use functions that make the programmer’s job much easier. Although it is hard to categorize these functions precisely, we can group the most frequently used ones into categories such as elementary math functions, trigonometric functions, complex numbers, random numbers, and basic plotting functions, although there are more than we can list here. Using the help command, you can easily review the descriptions of the functions and their example uses. For a list of all elementary math functions, simply type help elfun at the prompt in MATLAB. Most of the other built-in MATLAB functions are introduced and explained in subsequent chapters.

Some of the Elementary Math Functions

In this section, I present the exponential functions and some other important functions that are used for rounding and finding remainders of a division function.

Example 1-9. Calculate $$ y=frac{8 }{sqrt{27}} $$ in MATLAB.

Solution 1-9. If the following code is typed at the prompt, the answer will be obtained as follows.
> y=log2(8)/sqrt(27)
y =
    0.5774
>

Example 1-10. Find the values of x and y, where y = ⌈2.9⌉ + ⌊12.8⌋ and x =  mod (157,5).

Solution 1-10. For the first variable y, we are asked to find the sum of the upper integer of 2.9 and lower integer of 12.8. For the second variable x, we are supposed to find the remainder of the division of 157 by 5. The code that finds the solution is given here.
> y=ceil(2.9)+floor(12.8)
y =
    -9
> x=mod(157,5)
x =
     2
>

Trigonometric Functions

Commands for the trigonometric functions in MATLAB are very intuitive. These functions are listed in Tables 1-8 and 1-9.
Table 1-7

Additional Math Functions

Function

Explanation

fix

Rounds number toward zero

floor

Rounds number toward minus infinity

ceil

Rounds number toward plus infinity

round

Rounds number toward nearest integer

mod

Shows remainder after dividing

rem

Shows remainder division

sign

Returns -1,0, or 1 (Signum function)

Table 1-8

Trigonometric Functions in Radians

Command

Definition

sin

Sine

cos

Cosine

tan

Tangent

cot

Cotangent

sec

Secant

csc

Cosecant

Table 1-9

Trigonometric Functions in Degrees

Command

Definition

sind

Sine in degrees

cosd

Cosine in degrees

tand

Tangent in degrees

cotd

Cotangent in degrees

secd

Secant in degrees

cscd

Cosecant in degrees

Table 1-10

Some of the Built-in Functions Available in MATLAB

Function

Explanation

Example

fliplr()

Flips the array from left to right

fliplr('How 5')

isletter()

States whether the elements are alphabetical letters and returns either 0 or 1

isletter('trabson61of')

isspace()

States whether the place is an empty space and returns either 0 or 1

isspace('Now 12 ')

lower()

Converts strings to lowercase

lower('Hola MY friend')

num2str()

Converts numerical type to string

num2str('61')

sort()

Sorts the elements of the array, first the capital letters, and then the small letters

sort('HOW are you Jack')

str2num()

Converts string to numerical type

str2num('23')

strcat()

Adds up the strings horizontally

strcat('How','Are','You?34')

strcmp()

Compares the strings; if the strings are the same, it returns 1, else 0

strcmp('Hola','hola')

strcmpi()

Compares the strings without case-sensitivity; if the strings are the same, it returns 1, else 0

strcmpi('Hola','hola')

strfind()

Finds a string within another string

strfind('You are','are')

strncmp()

Compares the first n strings and returns either 0 or 1

strncmp('ill6','ill7',4)

strncmpi()

Compares the first n strings without case-sensitivity, and returns either 0 or 1

strncmpi('ill6','ilL6',4)

strvcat()

Adds up the strings vertically

strvcat('How','Are','You?34')

upper()

Converts strings to uppercase

upper('Holla My Friend')

Table 1-11

Integer Types

Class

Command

Signed 8-bit integer

int8

Signed 16-bit integer

int16

Signed 32-bit integer

int32

Signed 64-bit integer

int64

Unsigned 8-bit integer

uint8

Unsigned 16-bit integer

uint16

Unsigned 32-bit integer

uint32

Unsigned 64-bit integer

uint64

Table 1-12

A Cell Array with Six Cells

1

0

0

‘How are you?’

2015

0

1

0

0

0

1

‘Hola’

72

‘Alexander’

Table 1-13

Employee Data

Employee’s ID

5001

Employee’s name

Robert

Employee’s address

San Antonio, TX

Employee’s salary

39,900

Table 1-14

Some Basic Functions Used with Tables

Function

Explanation

Example

table

Creates tables from the workspace variables

table(Gender,Smoker)

readtable

Creates a table from a file

readtable(filename)

writetable

Writes a table to a file

writetable(Table, filename)

table2cell

Converts a table to a cell array

table2cell(Table)

struct2table

Converts a structure to a table

struct2table(struct)

Table 1-15

Functions Related to Graphics

Function

Explanation

title(‘Title’)

Adds title to the plot

text(x,y,’string’)

Writes string at the point (x,y)

gtext(‘Text’)

Inserts text in the figure manually

xlabel(‘x’)

Prints x horizontally on the plot

ylabel(‘y’)

Prints y vertically on the plot

legend(‘st1’,..,’stN’)

Labels each data as st1, … stN strings

grid

Shows the grids on the figure

hold

Keeps the current figure to plot on it

clf

Clears the figure

cla

Clears the axes

Table 1-16

Features of the plot Function

Index

Color

Index

Point Type

Index

Line Type

b

Blue

.

Point

-

Solid

g

Green

o

Circle

:

Dotted

r

Red

x

X-mark

-.

Dashdot

c

Cyan

+

Plus

--

Dashed

m

Magenta

Star

  

y

Yellow

s

Square

  

k

Black

d

Diamond

  

w

White

v

Triangle down

  
  

^

Triangle up

  
  

<

Triangle left

  
  

>

Triangle right

  
  

p

Pentagram

  
  

h

Hexagram

  
Table 1-17

A Cell Array with 12 Cells

Your

Friend

Is

Ihsan

34

56

52

55

32

20

56

61

Data Types

In MATLAB, the default data type is double. This means that anything entered at the prompt is saved as double unless otherwise specified.

We can divide the data types into two major categories in MATLAB: homogeneous data types and heterogeneous data types (Figure 1-4). Homogeneous data types include the same type of data, whereas the heterogeneous data types have mixed or complex data types.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig4_HTML.jpg
Figure 1-4

Data types

Homogeneous Data Types

Homogeneous data types have the same characteristics. These types may be characters, strings, integers, floating-point numbers, or logical data.

Characters and Strings

Characters are composed of strings. Letters, numbers, or symbols can be defined as characters in MATLAB. Characters can be defined by entering them between single quotation marks.
> Let="34"
Let =
34
> class(Let)
ans =
char
>
In this example, even though we define the variable Let as 34 having all numbers, due to the fact that these numbers are entered between the single quotation marks, MATLAB recognizes Let as a character. If the class command is used to display its class, we will see that it is of type character.
> H='How are you?'
H =
How are you?
> length(H)
ans =
    12
> class(H)
ans =
char
>

In the preceding example, the variable H is defined as a character of length 12. The variable is defined as a character by putting its name between the single quotation marks.

Example 1-11. Three variables are defined as ‘How are you?’, ‘the weather’, and ‘is it correct?’ for A, B, and C, respectively. We want to create a new character ‘How is the weather’ by using the given three variables alone. Write the code to achieve this task.

Solution 1-11. To this point, we have typed the commands in the command window. We can write the code in the editor and save it in the working directory of MATLAB. Then by just typing the name of the saved file, we can run the code. This code is written in editor and saved as CharEx.m. The following program can be used for this task.

CharEx.m
% Name of this file is CharEx.m
% This is Example 1-11
% This code gets some strings and puts them
% together for another string
A = 'How are you?';
B = 'the weather';
C = 'is it correct?';
NewOne = [A(1:4) C(1:3) B]

As shown, we extract the first four characters of A, the first three characters of C, and all of the B strings, and assign them into a new variable NewOne. If the percentage (%) symbol is put on a line, MATLAB ignores everything that comes after that % symbol, so this is used for commenting.

Once we run the code at the prompt, the following output will be obtained.
> CharEx
NewOne =
How is the weather
>
In MATLAB, there is a very useful command called char. Using this command, we can print all the characters defined by the American Standard Code for Information Interchange (ASCII) as shown in Figure 1-5.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig5_HTML.jpg
Figure 1-5

ASCII table

From 32 to 127, these characters can be viewed as it is shown in the solution to Example 1-12.

Example 1-12. Write a program that prints out the lowercase and uppercase letters from the ASCII table.

Solution 1-12. The following code can be used to accomplish the given task.

Letters.m
% Name of this file is Letters.m
% This is Example 1-12
% This code prints alphabet letters
Small   = char(97:122);
Capital = char(65:90);
fprintf('Small letters are : %s ',Small);
fprintf('Big letters are : %s ',Capital);
Then in the command window, once we run the code at the prompt, we obtain the following output:
> Letters
Small letters are : abcdefghijklmnopqrstuvwxyz
Big letters are : ABCDEFGHIJKLMNOPQRSTUVWXYZ
>

In the code for Letters.m, the fprintf function prints purple characters up to the % symbol. After that, the letter s tells MATLAB that after that time, strings will be printed that are called Small and Capital. The part cuts the line and goes to the next line during printing.

Example 1-13. Bob wants to send the message “Start sending messages at 8:30” to Alice in a secret way as an encrypted message. Write a program that encrypts and decrypts Bob’s message. (Hint: Use the ASCII table)

Solution 1-13. The encryption and decryption parts can be given as follows.

HidingMessage.m
% Name of this file is HidingMessage.m
% This is Example 1-13
% This code encrypts and decrypts a message
%Encryption starts here
Message = 'Start sending message at 8:30';
Encryp = double(Message)+3;
fprintf('Encrypted Message : %s ',char(Encryp))
%Decryption starts here
Decryp = Encryp-3;
fprintf('Decrypted Message : %s ',char(Decryp))
In this solution, the message is converted to the corresponding numbers in the ASCII table using the command double. We then add 3 to the corresponding numbers of each letter for encryption. This shifts each letter by 3 to the right in the ASCII table. After the message is encrypted, it is decrypted back to its original version by subtracting 3 from the encrypted values. Once we run the code at the prompt, we obtain the following output:
> HidingMessage
Encrypted Message : Vwduw#vhqglqj#phvvdjh#dw#;=63
Decrypted Message : Start sending message at 8:30
>

MATLAB provides very useful functions for manipulating strings or characters. Some of the most commonly used functions are listed in Table 1-10.

Numerical Data

There exist two different kinds of numerical data types in MATLAB: integers and floating-point numbers. Integers are comprised of signed and unsigned types. There are eight types of integers in total, as shown in Table 1-11. The difference between these types is the storage space that they occupy in memory. If it is possible to do your calculations with low bit integers, you could save space in memory. When higher bit integers are preferred, more memory will be needed.

To find the maximum or minimum values of integers within the computer, you just need to type intmax('classname'). For example, if we type the following
> intmax('int8')
ans =
  127
> intmin('int64')
ans =
 -9223372036854775808
>
we see the values of the highest 8-bit integer and the lowest 64-bit integer. Also,
> intmin('uint64')
ans =
           0
> intmax('uint64')
ans =
 18446744073709551615
>

shows the lowest and highest unsigned 64-bit integers in the preceding code, using the intmin and intmax commands.

There are two types of floating-point numbers; namely, double-precision and single-precision numbers. Double-precision floating-point numbers are the default type for all entered variables. Single-precision floating-point numbers occupy 32 bits in memory, whereas double-precision floating-point numbers occupy 64 bits. We can check the highest and lowest values using the same commands we used for integers earlier.
> realmax('double')
ans =
  1.7977e+308
> realmin('single')
ans =
  1.1755e-38
>

Logical Data

In MATLAB, along with many other programming languages, 1 represents the logical true and 0 represents the logical false.

Example 1-14. Write a program that includes two variables as logical values. One should be true, and the other should be false. Compare these values using the logical and and logical or operators.

Solution 1-14. The following code can be used to accomplish the given task.

LogicalEx.m
% Name of this file is LogicalEx.m
% This is Example 1-14
% This code works with logical values
Logical1 = 3>2 % if it is true, it is 1
Logical2 = 5<4 % if it is false, it is 0
CombineWithAnd = Logical1 && Logical2 % and
CombineWithOr = Logical1 || Logical2  % or
If we run the code, we obtain the following result.
> LogicalEx
Logical1 =
     1
Logical2 =
     0
CombineWithAnd =
     0
CombineWithOr =
     1
> class(CombineWithOr)
ans =
logical
>

Once we check the class of the variable CombineWithOr after running the code, as just shown, it is logical data. Hence, the logical data values can be either 0 or 1.

Symbolic Data

Symbolic data are used to perform algebraic calculations using MATLAB’s symbolic toolbox. There are two ways of defining a symbolic variable. One is to type syms and the other way is to type sym as shown here.
> syms x
> class(x)
ans =
    'sym'
> y=sym('y')
y =
y
> class(y)
ans =
    'sym'
>

In either method, we can create symbolic data types, and then apply some algebraic operations such as taking the integral or derivative of them.

Heterogeneous Data Types

In some cases, due to the nature of the task at hand, we need to use more complex data types that are obtained by combining more than one type of data. These mixed data types are often called heterogeneous data types. Heterogeneous data types are encountered as cell arrays, structure arrays, and dataset arrays (tables) in MATLAB.

Cell Arrays

A cell can be regarded as a data box, and a cell array is an array of cells. Using the cell function, it is possible to preallocate empty cell arrays. Elements can be indexed by using the cell arrays. As an example, if you type cell(3,2) at the prompt, a variable of cell class is created as shown here.
> CellAr1=cell(3,2)
CellAr1 =
    []    []
    []    []
    []    []
>
To determine its class, you just need to type class(CellAr1) for the case given.
> class(CellAr1)
ans =
cell
>

There are several ways of creating a cell array. You may either preallocate the cell array before assigning values to the array, which is the case shown earlier, or you can just define the array and use it without preallocation.

Example 1-15. Define a cell array that holds the data in Table 1-12.

Solution 1-15. There are two different ways of defining this cell array. In the first method, all of the elements can be assigned to a single variable, whereas in the second case, the elements should be defined one by one. Let us name the cell array My_cell_array. Then, type the following at the prompt;
> My_cell_array={eye(3),'How are you?',2015;'Hola',72,'Alexander'}
My_cell_array =
    [3x3 double]    'How are you?'    [     2015]
    'Hola'          [          72]    'Alexander'
>

As shown, the index of the cell array is defined within curly brackets.

Structures

The most significant distinction between structures and cell arrays is the indexing. Although cell arrays can be indexed in terms of the elements contained in them, it is not possible to loop through the elements of structures. In other words, data are stored in a field in structures.

One of two different methods can be followed to create a structure. One is using the struct function and the other one is using the dot operator.

Example 1-16. A company wants to save an employee’s information as shown in Table 1-13.

Write a program that stores the information given in Table 1-13.

Solution 1-16. One way of doing that is to create a structure array by using the struct function as shown here.

StructArrayEx.m
% Name of this file is StructArrayEx.m
% This is Example 1-16
% This code creates a structure
employer=struct('id',5001,'name','Robert','address',...
    'San Antonio, TX','salary',39900)
As seen in the preceding code, the data are entered next to one another and are separated by a comma within the struct function . Once the program is executed from the command window, the following output will be shown.
> StructArrayEx
employer =
  struct with fields:
         id: 5001
       name: 'Robert'
    address: 'San Antonio, TX'
     salary: 39900
>

Tables

The third class of heterogeneous data types is called tables. Tables are especially convenient for storing column-oriented data. It is possible to perform useful operations on tables such as creating tables, reading data from the tables, changing the content of the tables, and so on. Some basic table functions are shown in Table 1-14.

Example 1-17. In a workspace, there are three variables:

Name = [‘Alex’; ‘Slim’; ‘Bill’], Age = [35; 40; 45], and Height = [160; 165; 170].

Using these data, write a program to create a table. The table should then be saved in a MyTable.xlsx file.

Solution 1-17. The following code can be used to accomplish this task.

CreateTables.m
% Name of this file is CreateTables.m
% This is Example 1-17
% This code creates a table and
% saves it as an .xlsx file
Name = ['Alex';'Slim';'Bill'];
Age = [35; 40; 45];
Height = [160; 165; 170];
T = table(Name,Age,Height)
writetable(T,'MyTable.xlsx')
Once the code is executed, we obtain the following output.
> CreateTables
T =
  3×3 table
    Name    Age    Height
    ____    ___    ______
    Alex    35      160
    Slim    40      165
    Bill    45      170
>

The spreadsheet file was saved in the MyTable.xlsx file in the directory as well.

More complex applications are available for tables. Here, we have seen only a simple example to give an idea about the general concept.

Plotting Graphics

MATLAB is a very powerful tool for graphics and plotting. A wide range of drawing tools are available for tasks such as plotting in polar coordinates, logarithmic graphics, animated 3-D plots, volume visualization plots, and so on. This section deals with the basic plotting of functions in two dimensions and plotting multiple functions on a single coordinate system or on a single figure.

Single Plotting

The basic command for drawing a function in MATLAB is the plot function. The simplest form of the plot command is plot(y), where y depends on its index. The most common use of the plot function is in the form of plot(x,y), which is the Cartesian plot of an (x,y) pair.

Example 1-18. Plot the function y = 2sinsin (x) through the interval of 0 ≤ x ≤ π.

Solution 1-18. If x is defined as a vector from 0 to pi using the linspace command, then we can draw the corresponding values of y versus x. In the following code, the distance from 0 to pi is divided into 100 points. If we pick a large number of points such as 1,000, the graph will become more precise.
> x=linspace(0,pi,100);
> y=2.*sin(x);
> plot(x,y)
>
The code just given produces the output shown in Figure 1-6.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig6_HTML.jpg
Figure 1-6

Cartesian plot of y=2sin(x) where 0 ≤ x ≤ π

Various features of graphics such as title, x label, y label, and grids are available in MATLAB. These features are shown in Table 1-15.

There are some other features available that allow programmers to work with line styles, colors, and sizes, as shown in Table 1-16.

To create a regular plot using the plot function , different options can be included in the drawing.

There is a remarkable number of special functions available to create two-dimensional and three-dimensional plots in MATLAB. In the command window, if you type >help specgraph and press Enter, you will see which special functions are available in your version.

Multiple Plots

It is possible to draw multiple plots on a single figure. That can be achieved in two ways.

We might have multiple plots on the same coordinate system besides having separate plots on one figure. If you want to draw different functions on the same axes, you can do it either by using one single plot function, or using the hold command and multiple plot commands.

Example 1-19. Plot the function y = 2 sinx with grids. Then, keep the first graph and plot a second function given by y = coscos (x) within the same interval. Insert the labels for each data set, as well.

Solution 1-19. The desired plot can be obtained using the following program and the results are shown in Figure 1-7.
> x=linspace(0,pi,100);
> y=2.*sin(x);
> plot(x,y)
> hold
Current plot held
> y2=cos(x);
> plot(x,y2)
> title('Title comes here')
> xlabel('This is x label')
> ylabel('This is y label')
> legend('2sin(x)','cos(x)')
> grid on
>
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig7_HTML.jpg
Figure 1-7

Plots of the functions y=2sin(x) and y2=cos(x)

It is possible to draw multiple plots using different axes on the same figure via the subplot command as well.

Example 1-20. Plot the three functions given in Example 4-5 on different axes on the same figure using the subplot command.

Solution 1-20. The following program may be entered at the prompt to accomplish the given task.
> x=linspace(0,pi,200);
> subplot(3,1,1)
> plot(x,sin(x))
> subplot(312)
> plot(x,cos(x))
> subplot(3,1,3)
> plot(x,sin(x)+cos(x))
> grid on
>
As shown, subplot(312) is used instead of subplot(3,1,2). Both will produce the same result. Once the program is executed, the output shown in Figure 1-8 is obtained.
../images/483991_1_En_1_Chapter/483991_1_En_1_Fig8_HTML.jpg
Figure 1-8

Plots of the three functions on the same figure using subplot

Problems

  • 1.1. Calculate the result for the variable given by $$ y=frac{e^3}{14}+8sqrt{10} $$.

  • 1.2. If you type >>3+6-9 at the prompt and press Enter, to which variable will the result be assigned?

  • 1.3. Which of the following expressions can be a variable name? Check them by using the isvarname command.

  • Alexander, 2Hola, +Number, Good Job, How are, Bg_3, Exam6, Add*Or

  • 1.4. Using the help command in the command window, learn the details about the iskeyword function. Then, write the difference between the isvarname and iskeyword commands.

  • 1.5. What is the difference between the expressions >> disp(4) and >> disp('4') entered in the command window?

  • 1.6. Consider the formula given by F=m*a. Find the value of a when F=45, m=10 is specified.

  • 1.7. If the following is typed at the prompt

> Logica=islogical(5<6) && islogical(2>1)
  • what could be your comments about the variable Logica?

  • 1.8. Consider the variable, Numb = 3/8. Write this variable in the longE, shortG, hex, and rat formats.

  • 1.9. Consider the function y =  cos (2x), where x =0:pi/12:pi, and obtain the vector y.

  • 1.10. Let A = [2 1 − 3 − 3 0 5 8 4 50 ]. If B is given by the second row of A, and C is given by the intersection of the third column and the first two rows of A, obtain the values of B and C.

  • 1.11. Using Matrix A in Problem 2-2, a new matrix is to be obtained. The first row of A will be removed, and the first and third rows of the resulting matrix will be swapped, as well. What would be the new matrix?

  • 1.12. For y = ⌈−12.9⌉ + ⌊10.8⌋ and x =  mod (15, 9), find the values of y and x.

  • 1.13. For $$ f(x)=frac{2ast left({mathit{sin}}^2x+{mathit{cos}}^2x
ight)}{tanx} $$, calculate the value of $$ fleft(frac{pi }{3}
ight) $$ in radians and degrees.

  • 1.14. Plot the functions f1(x) = sinsin (2 * x), f2(x) = coscos (2 * x), and f3(x) = sinsin (2 * x) + coscos (2 * x) along the interval 0 ≤ x ≤ 2 * π on a single coordinate system.

  • 1.15. Three variables are defined as ‘champion Barcelona’, ‘is good’, and ‘place to go for fun’ corresponding to A, B, and C, respectively. You want to create a new statement, ‘Barcelona is good place to go’, using the given variables. Write a code to perform this task.

  • 1.16. Write a program that holds the data in Table 1-17.

Write a program to list the elements of the array, and then display the content of the cell graphically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.70.170