This document provides a 3 sentence summary of a short term training program on Matlab for beginners:
The training program covers basic Matlab topics like the desktop interface, variables, arithmetic operations, matrices and arrays. It explains how to create and manipulate numeric data, perform common operations element-wise and on whole matrices, and generate matrices using functions. The document also demonstrates how to index and slice arrays to access subsets of elements and concatenate arrays horizontally and vertically.
3. Desktop Basics
• When you start MATLAB, the desktop appears in its default layout.
• The desktop includes these panels:
• Current Folder — Access your files.
• Command Window — Enter commands at the command line,
indicated by the prompt (>>).
• Workspace — Explore data that you create or import from files.
• Command History — View or rerun commands that you entered
at the command line.
4.
5. Command Window
• As you work in MATLAB, you issue commands that create variables and call functions.
• For example, create a variable named a by typing this statement at the command line:
• a = 1
• MATLAB adds variable a to the workspace and displays the result in the Command
Window.
• a =
1
• Create a few more variables.
• b = 2
b =
2
• c = a + b
c =
3
• d = cos(a)
d =
0.5403
6. • When you do not specify an output variable, MATLAB uses the
variable ans, short for answer, to store the results of your calculation.
• sin(a)
ans =
0.8415
• If you end a statement with a semicolon, MATLAB performs the
computation, but suppresses the display of output in the Command
Window.
• e = a*b;
7. Numbers and arithmetic operations
• There are 3 kinds of numbers used in MATLAB:
integers
real numbers
complex numbers
• Integers are entered without the decimal point.
• xi = 10
xi =
10
• Real numbers are entered with the decimal point.
• xr = 10.01
xi =
10.0100
8. • Variables realmin and realmax denote the smallest and the largest
positive real numbers in MATLAB. For instance,
• Realmin
ans =
2.2251e-308
9. Complex Numbers
• Complex numbers have both real and imaginary parts, where the imaginary
unit is the square root of –1.
• sqrt(-1)
ans =
0 + 1.0000i
• To represent the imaginary part of complex numbers, use either i or j.
• i
ans =
0 + 1.0000i
• c = [3+4i, 4+3j, -i, 10j]
• c =
3.0000+4.0000i 4.0000+3.0000i 0-1.0000i 0+10.0000i
10. • In addition to classes of numbers mentioned above, MATLAB has three
variables representing the non-numbers:
• -Inf
• Inf
• NaN
• The –Inf and Inf are the IEEE representations for the negative and positive
infinity, respectively.
• Infinity is generated by overflow or by the operation of dividing by zero.
• The NaN standsfor the not-a-numberand is obtained as a result of the
mathematicallyundefined operations such as
0.0/0.0 or ∞-∞
.
11. Numbers and arithmetic operations….
Operation Symbol
addition +
subtraction -
multiplication *
division / or
exponentiation ^
13. WorkspaceVariables
• The workspace contains variables that you create within or import
into MATLAB from data files or other programs. For example, these
statements create variables A and B in the workspace.
• A = magic(4);
• B = rand(3,5,2);
• You can view the contents of the workspace using whos.
• whos
• Name Size Bytes Class
A 4x4 128 double
B 3x5x2 240 double
14. • The variables also appear in the Workspace pane on the desktop.
• Workspace variables do not persist after you exit MATLAB. Save your
data for later use with the save command,
save myfile.mat
• Saving preserves the workspace in your current working folder in a
compressed file with a .mat extension, called a MAT-file.
• To clear all the variables from the workspace, use the clear command.
• Restore data from a MAT-file into the workspace using load.
load myfile.mat
15. • To save your current workspace select Save Workspace as… from the
File menu.
• Another way of saving your workspace is to type save filename in the
Command Window. The following command save filename s saves
only the variable s.
• Another way to save your workspace is to type the command diary
filename in the Command Window. All commands and variables
created from now will be saved in your file. The following command:
diary off will close the file and save it as the text file.
• To load contents of the file named filename into MATLAB's workspace
type load filename in the Command Window.
16. Suppressing Output
• If you simply type a statement and press Return or Enter, MATLAB
automatically displays the results on screen.
• However, if you end the line with a semicolon, MATLAB performs the
computation, but does not display any output. This is particularly
useful when you generate large matrices.
• For example,
• A = magic(100);
17. Entering Long Statements
• If a statement does not fit on one line, use an ellipsis (three periods),
..., followed by Return or Enter to indicate that the statement
continues on the next line. For example,
• s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
• Blank spaces around the =, +, and - signs are optional, but they
improve readability.
18.
19. Matrices and Arrays
• MATLAB is an abbreviation for "matrix laboratory. "While other
programming languages mostly work with numbers one at a time,
MATLAB is designed to ,operate primarily on whole matrices and
arrays.
• All MATLAB variables are multidimensional arrays, no matter what
type of data. A matrix is a two-dimensional array often used for linear
algebra.
20. Array Creation
• To create an array with four elements in a single row, separate the
elements with either a comma (,) or a space.
• a = [1 2 3 4]
returns
• a =
1 2 3 4
• This type of array is a row vector.
• To create a matrix that has multiple rows, separate the rows with
semicolons.
• a = [1 2 3; 4 5 6; 7 8 10]
• a =
1 2 3
4 5 6
7 8 10
21. • Another way to create a matrix is to use a function, such as ones,
zeros, or rand. For example, create a 5-by-1 column vector of zeros.
• z = zeros(5,1)
• z =
0
0
0
0
0
22. Matrix and Array Operations
• MATLAB allows you to process all of the values in a matrix using a
single arithmetic operator or function.
• a + 10
• ans =
11 12 13
14 15 16
17 18 20
• sin(a)
• ans =
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
23. • To transpose a matrix, use a single quote ('):
• a'
• ans =
1 4 7
2 5 8
3 6 10
• You can perform standard matrix multiplication, which computes the inner
products between rows and columns, using the * operator. For example,
confirm that a matrix times its inverse returns the identity matrix:
• p = a*inv(a)
• p =
1.0000 0 -0.0000
0 1.0000 0
0 0 1.0000
• Notice that p is not a matrix of integer values.
24. • MATLAB stores numbers as floating-point values, and arithmetic operations
are sensitive to small differences between the actual value and its floating-
point representation.
• You can display more decimal digits using the format command:
• format long
p = a*inv(a)
• p =
1.000000000000000 0 -0.000000000000000
0 1.000000000000000 0
0 0 0.999999999999998
• Reset the display to the shorter format using
• format short
• format affects only the display of numbers, not the way MATLAB computes or
saves them.
25. • To perform element-wise multiplication rather than matrix multiplication
use the .* operator:
• p = a.*a
• p =
1 4 9
16 25 36
49 64 100
• The matrix operators for multiplication, division, and power each have a
corresponding array operator that operates element-wise. For example,
raise each element of a to the third power:
• a.^3
• ans =
1 8 27
64 125 216
343 512 1000
26. Concatenation
• Concatenation is the process of joining arrays to make larger ones. In
fact, you made your first array by concatenating its individual
elements.
• The pair, of square brackets [] is the concatenation operator.
• A = [a,a]
• A =
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
27. • Concatenating arrays next to one another using commas is called
horizontal concatenation. Each array must have the same number of
rows. Similarly, when the arrays have the same number of columns,
you can concatenate vertically using semicolons.
• A = [a; a]
• A =
1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
28. Array Indexing
• Every variable in MATLAB is an array that can hold many numbers.
When you want to access selected elements of an array, use indexing.
• For example, consider the 4-by-4 magic square A:
• A = magic(4)
• A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
29. • There are two ways to refer to a particular element in an array. The
most common way is to specify row and column subscripts, such as
• A(4 , 2)
• ans =
14
• Less common, but sometimes useful, is to use a single subscript that
traverses down each column in order:
• A(8)
• ans =
14
• Using a single subscript to refer to a particular element in an array is
called linear indexing.
30. • If you try to refer to elements outside an array on the right side of an
assignment statement, MATLAB throws an error.
• test = A(4,5)
• Attempted to access A(4,5); index out of bounds because size(A) =
[4,4].
• However, on the left side of an assignment statement, you can specify
elements outside the current dimensions. The size of the array
increases to accommodate the newcomers.
• A(4,5) = 17
• A =
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
31. • To refer to multiple elements of an array, use the colon operator, which
allows you to specify a range of the form start:end. For example, list the
elements in the first three rows and the second column of A:
• A(1:3,2)
• ans =
2
11
7
• The colon alone, without startor end values, specifies all of the elements
in that dimension. For example, select all the columns in the third row of A:
• A(3,:)
• ans =
9 7 6 12 0
32. • The colon operator also allows you to create an equally spaced vector
of values using the more general form start:step:end.
• B = 0:10:100
• B =
0 10 20 30 40 50 60 70 80 90 100
• If you omit the middle step, as in start:end, MATLAB uses the default
step value of 1.
33. Character Strings
• A character string is a sequence of any number of characters enclosed in single
quotes. You can assign a string to a variable.
• myText = 'Hello, world';
• If the text includes a single quote, use two single quotes within the definition.
• otherText = 'You''re right'
• otherText =
You're right
• myText and otherText are arrays, like all MATLAB variables. Their class or data
type is char, which is short for character.
• whos myText
• Name Size Bytes Class
myText 1x12 24 char
34. • You can concatenate strings with square brackets, just as you
concatenate numeric arrays.
• longText = [myText,' - ',otherText]
• longText =
Hello, world - You're right
• To convert numeric values to strings, use functions, such as num2str
or int2str.
• f = 71;
c = (f-32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']k
• tempText =
Temperature is 21.6667C
35. Sum, Transpose, and diag
• A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
• MATLAB displays the matrix you just entered:
• A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
• The special properties of a magic square have to do with the various
ways of summing its elements. If you take the sum along any row or
column, or along either of the two main diagonals, you will always get
the same number. Let us verify that using MATLAB.
36. • sum(A)
• ans =
34 34 34 34
• It has computed a row vector containing the sums of the columns of A.
• Each of the columns has the same sum, the magic sum, 34.
• How about the row sums? MATLAB has a preference for working with the
columns of a matrix, so one way to get the row sums is to transpose the
matrix, compute the column sums of the transpose, and then transpose
the result.
• (sum(A’))’
• ans =
34
34
34
34
37. • The sum of the elements on the main diagonal is obtained with the
sum and the diag functions:
• sum(diag(A))
• ans =
34
• The other diagonal, the so-called antidiagonal, is not so important
mathematically, so MATLAB does not have a ready-made function for
it. But a function originally intended for use in graphics, fliplr, flips a
matrix from left to right:
• sum(diag(fliplr(A)))
• ans =
34
38. • B = magic(4)
• B =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
• If it is required to swap the two rows or columns
• A = B(:,[1 3 2 4])
• This subscript indicates that—for each of the rows of matrix B—reorder the
elements in the order 1, 3, 2, 4. It produces:
• A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
39. Generating Matrices
• Z = zeros(2,4)
• Z =
0 0 0 0
0 0 0 0
• F = ones(3,3)
• F =
1 1 1
1 1 1
1 1 1
• N = rand(1,10)
• N = fix(N)
40. Variables
• Like most other programming languages, the MATLAB language provides
mathematicalexpressions,but unlike most programming languages, these
expressions involve entire matrices
• MATLAB does not require any type declarations or dimension statements.
• When MATLAB encounters a new variable name, it automaticallycreates
the variable and allocates the appropriate amount of storage. If the
variable already exists, MATLAB changes its contents and, if necessary,
allocates new storage.
• For example, num_students = 25, creates a 1-by-1 matrix named
num_students and stores the value 25 in its single element.
• To view the matrix assigned to any variable, simply enter the variable
name.
41. • Variable names consist of a letter, followed by any number of letters,
digits, or underscores.
• MATLAB is case sensitive; it distinguishes between uppercase and
lowercase letters. A and a are not the same variable.
42. Numbers
• MATLAB uses conventional decimal notation, with an optional
decimal point and leading plus or minus sign, for numbers.
• Scientific notation uses the letter e to specify a power-of-ten scale
factor.
• Imaginary numbers use either i or j as a suffix.
• Some examples of legal numbers are
• 3 -99 0.0001
9.6397238 1.60210e-20 6.02252e23
1i -3.14159j 3e5i
43. Matrix Operators
• Expressions use familiar arithmetic operators and precedence rules.
• + Addition
• - Subtraction
• * Multiplication
• / Division
• Left division
• ^ Power
• ' Transpose
• ( ) Specify evaluation order
44. Array Operators
• When they are taken away from the world of linear algebra, matrices
become two-dimensional numeric arrays.
• Arithmetic operations on arrays are done element by element. This means
that addition and subtraction are the same for arrays and matrices,but
that multiplicativeoperations are different. MATLAB uses a dot, or decimal
point, as part of the notation for multiplicativearray operations.
• + Addition
• - Subtraction
• .* Element-by-element multiplication
• ./ Element-by-element division
• . Element-by-element left division
• .^ Element-by-element power
45. Building Tables
• Array operations are useful for building tables. Suppose n is the column vector
• n = (0:9)';
• pows = [n n.^2 2.^n]
builds a table of squares and powers of 2:
• pows =
0 0 1
1 1 2
2 4 4
3 9 8
4 16 16
5 25 32
6 36 64
7 49 128
8 64 256
9 81 512
46. Functions
• MATLAB provides a large number of standard elementary mathematical
functions, including abs, sqrt, exp, and sin.
• Taking the square root or logarithm of a negative number is not an error;
the appropriate complex result is produced automatically.
• MATLAB also provides many more advanced mathematicalfunctions,
including Bessel and gamma functions. Most of these functions accept
complex arguments. For a list of the elementary mathematical functions,
type
• help elfun
• For a list of more advanced mathematicaland matrix functions, type
help specfun
help elmat
47. • Some of the functions, like sqrt and sin, are built in.
• Built-in functions are part of the MATLAB core so they are very
efficient, but the computational details are not readily accessible.
• Other functions are implemented in the MATLAB programing
language, so their computational details are accessible.
• There are some differences between built-in functions and other
functions.
• For example, for built-in functions, you cannot see the code. For
other functions, you can see the code and even modify it if you want.
48. The format Function
• The format function controls the numeric format of the values displayed.
• The function affects only how numbers are displayed, not how MATLAB software
computes or saves them. Here are the different formats, together with the resulting
output produced from a vector x with components of different magnitudes.
• Syntax
format
format type
• x = [4/3 1.2345e-6]
• format short (Scaled fixed point format, with 5 digits)
1.3333 0.0000
• format short e (Floating point format, with 5 digits.)
1.3333e+000 1.2345e-006
• format short g (Best of fixed or floating point, with 5 digits.)
1.3333 1.2345e-006
• format short eng (Engineering format that has at least 5 digits and a power that is a
multiple of three)
1.3333e+000 1.2345e-006
49. • format long (Scaled fixed point format, with 15 digits)
1.33333333333333 0.00000123450000
• format long e
1.333333333333333e+000 1.234500000000000e-006
• format long g
1.33333333333333 1.2345e-006
• format bank
1.33 0.00
• format rat
4/3 1/810045
• format hex
3ff5555555555555 3eb4b6231abfd271
50. • If the largest element of a matrix is larger than 103 or smaller than
10-3, MATLAB applies a common scale factor for the short and long
formats.
• In addition to the format functions shown above
• format compact suppresses many of the blank lines that appear in the
output. This lets you view more information on a screen or window. If
you want more control over the output format, use the sprintf and
fprintf functions.
• format loose
• View the current format by typing
get(0,’format’)
51. Command Line Editing
• Various arrow and control keys on your keyboard allow you to recall, edit,
and reuse statementsyou have typed earlier.
• For example, suppose you mistakenly enter
• rho = (1 + sqt(5))/2
• You have misspelled sqrt. MATLAB responds with
• Undefined function 'sqt' for input arguments of type 'double'.
• Instead of retyping the entire line, simply press the ↑ key. The statement
you typed is redisplayed. Use the ← key to move the cursor over and insert
the missing r. Repeated use of the ↑ key recalls earlier lines. Typing a few
characters, and then pressing the ↑ key finds a previous line that begins
with those characters. You can also copy previously executed statements
from the Command History.
52. The m-files
• Files that contain a computer code are called the m-files.
• There are two kinds of m-files: the script files and the function files.
• Script files do not take the input arguments or return the output
arguments while The function files may take input arguments or return
output arguments.
• To create m-file click File -> New -> Script
• MATLAB Editor/Debugger screen is opened.
• Here we will type our code, can make changes, etc. Once we are
done with typing, click on File, in the MATLAB Editor/Debugger
screen and select Save As… .
53. The m-files…
• Chose a name for the file, e.g., filename.m and click on Save.
• Make sure that your file is saved in the directory that is in MATLAB's search
path.
• To open the m-file from within the Command Window type edit
filename and then press Enter or Return key.
• Example of Function of descending order.
54. Inline functions and the feval command
• Sometimes it is handy to define a function that will be used during the
current MATLAB session only.
• MATLAB has a command inline used to define the so-called inline functions
in the Command Window.
• f = inline('sqrt(x.^2+y.^2)','x','y')
f =
Inline function:
f(x,y) = sqrt(x.^2+y.^2)
55. Inline functions and the feval command…
• We can evaluate this function in a usual way
• f (3,4)
ans =
5
• This function also works with arrays.
• A = [1 2;3 4];
• B = ones(2);
• C = f(A, B)
C =
1.4142 2.2361
3.1623 4.1231
56. Inline functions and the feval command…
• Some functions take as the input argument a name of another function, which is
specified as a string.
• In order to execute function specified by string we use the command feval as shown
below
• feval('functname', input parameters of function functname)
57. Control flow
• To control the flow of commands, the makers of MATLAB supplied
four devices a programmer can use while writing his/her computer
code
• the for loops
• the while loops
• the if-else-end constructions
• the switch-case constructions
58. for loops
• Syntax of the for loop is shown below
for k = array
commands
end
• The commands between the for and end statements are executed for all
values stored in the array.
• Suppose that one-need values of the sine function at eleven evenly spaced
points πn/10, for n = 0, 1, …, 10. To generate the numbers in question one
can use the for loop
for n=0:10
x(n+1) = sin(pi*n/10);
end
59. for loops…
• The for loops can be nested
H = zeros(5);
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end
• H
H =
1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
60. for loops…
• The for loop should be used only when other methods cannot be applied.
Consider the following problem.
• Generate a 10-by-10 matrix A = [akl], where akl = sin(k)cos(l). Using nested
loops one can compute entries of the matrix A using the following code
A = zeros(10);
for k=1:10
for l=1:10
A(k,l) = sin(k)*cos(l);
end
end
61. for loops…
• A loop free version might look like this
k = 1:10;
A = sin(k)'*cos(k);
• First command generates a row array k consisting of integers 1, 2, … , 10.
• The command sin(k)‘ creates a column vector while cos(k) is the row
vector.
• Components of both vectors are the values of the two trig functions
evaluated at k.
• Code presented above illustrates a powerful feature of MATLAB called
vectorization. This technique should be used whenever it is possible.
62. while loops
• Syntax of the while loop is
while expression
statements
End
• This loop is used when the programmer does not know the number
of repetitions a priori.
• The number π is divided by 2. The resulting quotient is divided by 2
again. This process is continued till the current quotient is less than
or equal to 0.01. What is the largest quotient that is greater than
0.01 ?
q = pi;
while q > 0.01
q = q/2;
end
63. The if-else-endconstructions
• Syntax of the simplest form of the construction is
if expression
commands
End
• This construction is used if there is one alternative only.
• Two alternatives require the construction
if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end
64. The if-else-endconstructions…
• If there are several alternatives, we use the following construction
if expression1
commands (evaluated if expression 1 is true)
elseif expression 2
commands (evaluated if expression 2 is true)
elseif …
...
else
commands (executed if all previous expressions evaluate to false)
end
65. The if-else-endconstructions…
• Chebyshev polynomials Tn(x), n = 0, 1, … of the first kind are of great
importance in numerical analysis. They are defined recursively as follows
Tn(x) = 2xTn-1(x) – Tn-2(x), n = 2, 3, … , T0(x) = 1, T1(x) = x.
• Implementation of this definition is easy
66. The if-else-end constructions…
function T = ChebT(n)
% Coefficients T of the nth Chebyshev polynomial of the first kind. They are
stored in the descending order of powers.
t0 = 1;
t1 = [1 0];
if n == 0
T = t0;
elseif n == 1;
T = t1;
else
for k=2:n
T = [2*t 0] - [0 0 t0];
t0 = t1;
t1 = T;
end
end
68. The switch-case construction
• Syntax of the switch-case construction is
switch expression (scalar or string)
case value1 (executes if expression evaluates to value1)
commands
case value2 (executes if expression evaluates to value2)
commands
.
.
.
otherwise
statements
end
69. The switch-case construction…
• Switch compares the input expression to each case value. Once the match
is found it executes the associated commands.
• a random integer number x from the set {1, 2, … , 10} is generated. If x = 1
or x = 2, then the message Probability = 20% is displayed to the screen. If x
= 3 or 4 or 5, then the message Probability = 30% is displayed, otherwise
the message Probability = 50% is generated.
x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10}
switch x
case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%');
otherwise
disp('Probability = 50%');
end
70. The switch-case construction…
• Here are new MATLAB functions that are used in earlier code (file fswitch)
• rand – uniformly distributed random numbers in the interval (0, 1)
• ceil – round towards plus infinity infinity
• disp – display string/array to the screen
• Let us test this code ten times
for k = 1:10
fswitch
end
71. Relations and logical operators
• Comparisons in MATLAB are performed with the aid of the following operators
Operator Description
< Less than
<= Less than or equal to
> Greater
>= Greater or equal to
== Equal to
~= Not equal to
72. Relations and logical operators…
• Operator == compares two variables and returns ones when they are equal
and zeros otherwise.
• a= [1 1 3 4 1]
a =
1 1 3 4 1
• ind = (a == 1)
ind =
1 1 0 0 1
• b = a(ind)
b =
1 1 1
73. Relations and logical operators…
• We can obtain the same result using function find
ind = find(a == 1)
ind =
1 2 5
• Variable ind now holds indices of those entries that satisfy the imposed
condition. To extract all ones from the array a use
• b = a(ind)
b =
1 1 1
74. Relations and logical operators…
• There are three logical operators available in MATLAB
• If one wants to select all entries x that satisfy the inequalities x >=1
or x < -0.2
• x = randn(1,7)
x =
-0.4326 -1.6656 0.1253 0.2877 -1.1465 1.1909 1.1892
Operator Description
| And
& Or
~ Not
75. Relations and logical operators…
• ind = (x >= 1) | (x < -0.2)
ind =
1 1 0 0 1 1 1
• y = x(ind)
y =
-0.4326 -1.6656 -1.1465 1.1909 1.1892
• In addition to relational and logical operators MATLAB has several logical
functions designed for performing similar tasks. These functions return 1
(true) if a specific condition is satisfied and 0 (false) otherwise.
76. Relations and logical operators…
• isempty(y)
ans =
0
returns 0 because the array y of the last example is not empty.
• isempty([ ])
ans =
1
returns 1 because the argument of the function used is the empty array [ ].
77. Rounding to integers. Functions ceil, floor,
fix and round
Function Description
floor Round towards minus infinity
ceil Round towards plus infinity
fix Round towards zero
round Round towards nearest integer
78. Rounding to integers. Functions ceil,
floor, fix and round…
• To illustrate differences between these functions let us create first a two-
dimensional array of random numbers that are normally distributed (mean
= 0, variance = 1) using another MATLAB function randn
• randn('seed', 0) % This sets the seed of the random numbers generator
to zero
• T = randn(5)
• T =
1.1650 1.6961 -1.4462 -0.3600 -0.0449
0.6268 0.0591 -0.7012 -0.1356 -0.7989
0.0751 1.7971 1.2460 -1.3493 -0.7652
0.3516 0.2641 -0.6390 -1.2704 0.8617
-0.6965 0.8717 0.5774 0.9846 -0.0562
79. Rounding to integers. Functions ceil, floor, fix
and round…
• A = floor(T)
• B = ceil(T)
• C = fix(T)
• D = round(T)
• It is worth mentioning that the following identities
floor(x) = fix(x) for x > 0
ceil(x) = fix(x) for x < 0
hold true
• rep4.m
80. MATLAB graphics
• MATLAB has several high-level graphical routines. They allow a user
to create various graphical objects including two- and three-
dimensional graphs, graphical user interfaces (GUIs), movies, to
mention the most important ones.
81. 2-D graphics
• Basic function used to create 2-D graphs is the plot function. This function takes a
variable number of input arguments.
• Example: the graph of the rational function 𝑓 𝑥 =
𝑥
1+𝑥2, -2<x<2, will be ploted using a
variable number of points on the graph of f(x)
82. 2-D graphics…
• % Script file graph1.
for n=1:2:5
n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
plot(x,y,'r')
title(sprintf('Graph %g. Plot based upon n = %g points.' ...,
(n+1)/2, n10))
axis([-2,2,-.8,.8])
xlabel('x')
ylabel('y')
83. 2-D graphics…
• The loop for is executed three times. Therefore, three graphs of the same
function will be displayed in the Figure Window.
• A MATLAB function linspace(a, b, n) generates a one-dimensional array of
n evenly spaced numbers in the interval [a b].
• The y-ordinates of the points to be plotted are stored in the array y.
• Command plot is called with three arguments: two arrays holding the x-
and the y-coordinates and the string 'r', which describes the color (red) to
be used to paint a plotted curve.
• We should notice a difference between three graphs created by this file.
There is a significant difference between smoothness of graphs 1 and 3.
84. 2-D graphics…
• MATLAB has several colors you can use to plot graphs:
y yellow
M magenta
c cyan
r red
g green
b blue
w white
k black
85. 2-D graphics…
• Based on the visual observation we can say: "more points you supply
the smoother graph is generated by the function plot".
• Function title adds a descriptive information to the graphs generated
by this m-file and is followed by the command sprintf.
• sprintf takes here three arguments: the string and names of two
variables printed in the title of each graph.
• To specify format of printed numbers we use here the construction
%g, which is recommended for printing integers
86. 2-D graphics…
• The command axis tells MATLAB what the dimensions of the box
holding the plot are.
• To add more information to the graphs created here, we label the x-
and the y-axes using commands xlabel and the ylabel, respectively.
Each of these commands takes a string as the input argument.
• Function grid adds the grid lines to the graph.
• The last command used before the closing end is the pause
command.
• The command pause(n) holds on the current graph for n seconds
before continuing, where n can also be a fraction.
• If pause is called without the input argument, then the computer
waits to user response. For instance, pressing the Enter key will
resume execution of a program.
87. 2-D graphics…
• Function subplot is used to plot of several graphs in the same Figure
Window. Here is a slight modification of the m-file graph1
• Script file graph2
• The command subplot is called here with three arguments. The first
two tell MATLAB that a 2-by-2 array consisting of four plots will be
created. The third parameter is the running index telling MATLAB
which subplot is currently generated.
88. 2-D graphics…
• Using command plot we can display several curves in the same
Figure Window.
% Script file graph3.
% Graphs of two ellipses
% x(t) = 3 + 6cos(t), y(t) = -2 + 9sin(t)
% and
% x(t) = 7 + 2cos(t), y(t) = 8 + 6sin(t).
• There are several new MATLAB commandswhich are used in this file.
• They are used here to enhance the readability of the graph.
89. 2-D graphics…
• The command in line 6 begins with h1 = plot…
• Variable h1 holds an information about the graph we generate and is
called the handle graphics.
• Command set used in the next line allows a user to manipulate a
plot. Note that this command takes as the input parameter the
variable h1.
• We change thickness of the plotted curves from the default value to
a width of our choice, namely 1.25.
• In the next line we use command axis to customize plot.
• We chose option 'square' to force axes to have square dimensions.
Other available options are: 'equal', 'normal', 'ij', 'xy', and 'tight'.
90. 2-D graphics…
• If function axis is not used, then the circular curves are not
necessarily circular. To justify this let us plot a graph of the unit circle
of radius 1 with center at the origin
t = 0:pi/100:2*pi;
x = cos(t);
y = sin(t);
plot(x,y)
• Function get takes as the first input parameter a variable named gca
= get current axis.
• Variable h = get(gca, … ) is the graphics handle of this axis.
91. 2-D graphics…
• With the information stored in variable h, we change the font size
associated with the x-axis using the 'FontSize' string followed by a
size of the font we wish to use.
• Invoking function set in line 12, we will change the tick marks along
the x-axis using the 'XTick' string followed by the array describing
distribution of marks.
• We can also make changes in the title of the plot.
• It should be obvious from the short discussion presented here that
two MATLAB functions get and set are of great importance in
manipulating graphs.
92. 2-D graphics…
• MATLAB has several functions designed for plotting specialized 2-D
graphs.
• A partial list of these functions is included here fill, polar, bar, barh,
pie, hist, compass, errorbar, stem, and feather.
• In this example function fill is used to create a well-known object
n = -6:6;
x = sin(n*pi/6);
y = cos(n*pi/6);
fill(x, y, 'r')
axis('square')
title('Graph of the n-gone')
text(-0.45,0,'What is a name of this object?')
93. 2-D graphics…
• Function fill takes three input parameters - two arrays, named here x
and y. They hold the x- and y-coordinates of vertices of the polygon
to be filled. Third parameter is the user-selected color to be used to
paint the object.
• A new command that appears in this short code is the text
command. It is used to annotate a text. First two input parameters
specify text location. Third input parameter is a text, which will be
added to the plot.
94. 3-D Graphics
• MATLAB has several built-in functions for plotting three-dimensional
objects. Some of them are:
plot3 to plot curves in space
mesh mesh surfaces
surf surfaces
contour contour plots
• For any help type help graph3d in the Command Window
95. 3-D Graphics…
• Let r(t) = < t cos(t), t sin(t), t >, -10π < t > 10π, be the space curve.
We plot its graph over the indicated interval using function plot3
• Script file graph4
• Function plot3 takes three input parameters – arrays holding
coordinates of points on the curve to be plotted.
96. 3-D Graphics
• Function mesh is intended for plotting graphs of the 3-D mesh
surfaces.
• function meshgrid generates two two-dimensional arrays for 3-D
plots.
• Suppose that one wants to plot a mesh surface over the grid that is
defined as the Cartesian product of two sets
x = [0 1 2];
y = [10 12 14];
The meshgrid command applied to the arrays x and y creates two
matrices.
[xi, yi] = meshgrid(x,y)
97. 3-D Graphics…
• Note that the matrix xi contains replicated rows of the array x while
yi contains replicated columns of y.
• The z-values of a function to be plotted are computedfrom arrays xi
and yi.
• In this example we will plot the hyperbolic paraboloid z = y2 – x2
over the square –1 < x < 1, –1 < y < 1
x = -1:0.05:1;
y = x;
[xi, yi] = meshgrid(x,y);
zi = yi.^2 – xi.^2;
mesh(xi, yi, zi)
axis off
98. 3-D Graphics…
• Now to plot the graph of the mesh surface together with the
contour plot beneath the plotted surface use function meshc
meshc(xi, yi, zi)
axis off
99. 3-D Graphics…
• Function surf is used to visualize data as a shaded surface.
• Computer code in the m-file graph5 should help us to learn some
finer points of the 3-D graphics in MATLAB
• % Script file graph5.
• command surfc plots a surface together with the level lines beneath.
• Unlike the command surfc the command surf plots a surface only
without the level curves.
• Command colormap is used to paint the surface using a user-
supplied colors. If the command colormap is not added, MATLAB
uses default colors.
100. 3-D Graphics…
• Here is a list of color maps that are available in MATLAB
hsv - hue-saturation-value color map
hot - black-red-yellow-white color map
gray - linear gray-scale color map
bone - gray-scale with tinge of blue color map
copper - linear copper-tonecolor map
pink - pastel shades of pink color map
white - all white color map
flag - alternating red, white, blue, and black color map
lines - color map with the line colors
101. 3-D Graphics…
colorcube - enhanced color-cube color map
vga - windows colormap for 16 colors
jet - variant of HSV
prism - prism color map
cool - shades of cyan and magentacolor map
autumn - shades of red and yellow color map
spring - shades of magenta and yellow color map
winter - shades of blue and green color map
summer - shades of green and yellow color map
102. 3-D Graphics…
• Command shading (see line 7) controls the color shading used to
paint the surface. Command in question takes one argument.
shading flat sets the shading of the current graph to flat
shading interp sets the shading to interpolated
shading faceted sets the shading to faceted, which is the default.
• Command view (see line 8) is the 3-D graph viewpoint specification.
It takes a three-dimensional vector, which sets the view angle in
Cartesian coordinates.
103. 3-D Graphics…
• Command figure prompts MATLAB to create a new Figure Window
in which the level lines will be plotted.
• In order to enhance the graph, we use command contourf instead of
contour. The former plots filled contour lines while the latter
doesn't.
• On the same line we use command hold on to hold the current plot
and all axis properties so that subsequent graphing commands add
to the existing graph.
• First command on line 25 returns matrix c and graphics handle h that
are used as the input parameters for the function clabel, which adds
height labels to the current contourplot.
104. Animation
• In addition to static graphs one can put a sequence of graphs in motion.
• In other words, we can make a movie using MATLAB graphics tools.
• To learn how to create a movie, let us analyze the m-file firstmovie.
105. Animation…
• Script file firstmovie.
• Command moviein, on line 1, with an integral parameter, tells
MATLAB that a movie consistingof five frames is created in the body
of this file.
• Consecutive frames are generated inside the loop for.
• getframe command means each frame of the movie is stored in the
column of the matrix m.
• Command movie(m) tells MATLAB to play the movie just created and
saved in columns of the matrix m.
106. Command Sphere and Cylinder
• MATLAB has some functions for generating special surfaces. We will
be concerned mostly with two functions- sphere and cylinder.
• The command sphere(n) generates a unit sphere with center at the
origin using (n+1)2 points.
• If function sphere is called without the input parameter, MATLAB
uses the default value n = 20.
• We can translate the center of the sphere easily.
• In the following example we will plot graph of the unit sphere with
center at (2, -1, 1)
[x,y,z] = sphere(30);
surf(x+2, y-1, z+1)
107. Command Sphere and Cylinder…
• Function sphere together with function surf or mesh can be used to
plot graphs of spheres of arbitrary radii. Also, they can be used to
plot graphs of ellipsoids.
108. Command Sphere and Cylinder…
• Function cylinder is used for plotting a surface of revolution. It takes
two (optional) input parameters.
• In the following command cylinder(r, n) parameter r stands for the
vector that defines the radius of cylinder along the z-axis and n
specifies a number of points used to define circumferenceof the
cylinder.
• Default values of these parameters are r = [1 1] and n = 20.
• A generated cylinder has a unit height.
• The following command
cylinder([1 0])
title('Unit cone')
109. Command Sphere and Cylinder…
• plots a cone with the base radius equal to one and the unit height.
• Example: we will plot a graph of the surface of revolution obtained
by rotating the curve r(t) = < sin(t), t >, 0<t>π about the y-axis.
• Graphs of the generating curve and the surface of revolution are
created using a few lines of the computer code
t = 0:pi/100:pi;
r = sin(t);
plot(r,t)
111. Printing MATLAB Graphics
• To send a current graph to the printer click on File and next select
Print from the pull down menu.
• Once this menu is open we can preview a graph to be printed be
selecting the option PrintPreview…
• We can also send the graph to the printer using the print command
x = 0:0.01:1;
plot(x, x.^2)
print
112. Printing MATLAB Graphics…
• We can print the graphics to an m- file using built-in device drivers.
• A fairly incomplete list of these drivers is included here:
-depsc Level 1 color Encapsulated PostScript
-deps2 Level 2 black and white Encapsulated PostScript
-depsc2 Level 2 color EncapsulatedPostScript
• Suppose that one wants to print a current graph to the m-file Figure1
using level 2 color Encapsulated PostScript. This can be accomplished
by executing the following command
print –depsc2 Figure1
113. Printing MATLAB Graphics…
• You can put this command either inside your m-file or execute it from
within the Command Window.