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>.
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.
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.
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.
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 .
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.
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.
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
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.
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.
We use the compact format throughout this book to save space.
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.
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
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
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.
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
Special Matrices
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) |
Colon Operator
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 > |
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 > |
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.
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.
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 in MATLAB.
Example 1-10. Find the values of x and y, where y = ⌈2.9⌉ + ⌊12.8⌋ and x = mod (157,5).
Trigonometric Functions
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) |
Trigonometric Functions in Radians
Command | Definition |
---|---|
sin | Sine |
cos | Cosine |
tan | Tangent |
cot | Cotangent |
sec | Secant |
csc | Cosecant |
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 |
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') |
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 |
A Cell Array with Six Cells
1 | 0 | 0 | ‘How are you?’ | 2015 |
0 | 1 | 0 | ||
0 | 0 | 1 | ||
‘Hola’ | 72 | ‘Alexander’ |
Employee Data
Employee’s ID | 5001 |
---|---|
Employee’s name | Robert |
Employee’s address | San Antonio, TX |
Employee’s salary | 39,900 |
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) |
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 |
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 |
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.
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
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.
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.
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.
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.
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.
shows the lowest and highest unsigned 64-bit integers in the preceding code, using the intmin and intmax commands.
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.
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
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
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.
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.
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.
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 ≤ π.
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.
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.
Problems
1.1. Calculate the result for the variable given by .
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
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 , calculate the value of 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.