2. MATLAB (matrix laboratory) is a numerical computing environment
and fourth generation programming language.
Developed by Math Works.
MATLAB allows matrix manipulations, plotting of functions and data,
implementation of algorithms creation of user interfaces and interfacing
with programs written in other languages, including C, C++,JAVA and
Fortron.
MATLAB® is a high-level language and interactive environment for
numerical computation, visualization, and programming.
Using MATLAB, you can analyze data, develop algorithms, and create
models and applications.
The language, tools, and built-in math functions enable you to explore
multiple approaches and reach a solution faster than with spreadsheets
or traditional programming languages, such as C/C++ or Java.
MATLAB BASICS2
3. You can use MATLAB for a range of applications, including signal
processing and communications, image and video processing, control
systems, test and measurement, computational finance, and
computational biology.
More than a million engineers and scientists in industry and academia
use MATLAB, the language of technical computing.
Advantages of MATLAB
Ease of use
Platform independence
Predefined functions
Plotting
Disadvantages of MATLAB
Can be slow
Commercial software
MATLAB BASICS3
4. Matlab Screen
Command Window
type commands
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
view past commands
save a whole session
using diary
MATLAB BASICS4
5. MATLAB BASICS6
Array: A collection of data values organized into
rows and columns, and known by a single name.
Row 1
Row 2
Row 3
Row 4
Col 1 Col 2 Col 3 Col 4 Col 5
arr(3,2)
MATLAB BASICS
8. MATLAB BASICS
8
Keyword Search of Help Entries
>> lookfor who
newton.m: % inputs: 'x' is the number whose
square root we seek
testNewton.m: % inputs: 'x' is the number
whose square root we seek
WHO List current variables.
WHOS List current variables, long form.
TIMESTWO S-function whose output is two times
its input.
>> whos
Name Size Bytes Class Attributes
ans 1x1 8 double
fid 1x1 8 double
i 1x1 8 double
9. MATLAB BASICS
Arrays
The fundamental unit of data in MATLAB
Scalars are also treated as arrays by
MATLAB (1 row and 1 column).
Row and column indices of an array start
from 1.
Arrays can be classified as vectors and
matrices.
MATLAB BASICS
9
10. MATLAB BASICS
Vector: Array with one dimension
Matrix: Array with more than one
dimension
Size of an array is specified by the number
of rows and the number of columns, with
the number of rows mentioned first (For
example: n x m array).
Total number of elements in an array is the
product of the number of rows and the
number of columns.
MATLAB BASICS
10
12. MATLAB BASICS
12
32
54
7
6
1
10
8 9
11 12
4
7
1
10
2
5
MATLAB BASICS
8
11
Multidimensional Arrays
• A two dimensional array with m rows and n
columns will occupy mxn successive locations in
the computer’s memory. MATLAB always
allocates array elements in column major
order.
a= [1 2 3; 4 5 6; 7 8 9; 10 11 12];
a(5) = a(1,2) = 2
• A 2x3x2 array of three dimensions
c(:, :, 1) = [1 2 3; 4 5 6 ];
c(:, :, 2) = [7 8 9; 10 11 12];
13. MATLAB BASICS
Variables
Variable names must begin with a letter,
followed by any combination of letters, numbers
and the underscore (_) character.
The MATLAB language is Case Sensitive. NAME,
name and Name are all different variables.
Give meaningful (descriptive and easy-to-remember)
names for the variables. Never define a variable with the
same name as a MATLAB function or command.
MATLAB BASICS
13
14. Variables and Workspace
• Information is stored in
variables.
>> a = 10
a =
10
>>
Real numbers
Matlab is case sensitive (a A)
MATLAB BASICS
15
15. • Information is stored in
variables.
» a = 3+2i
a =
3.0000 + 2.0000i
Imaginary numbers
MATLAB BASICS
16
16. Variables and Workspace
• Variables are stored in the
workspace
» who
Your variables are:
a
MATLAB BASICS
17
17. » whos
Name Size Bytes Class
a 1x1 8 double array
Grand total is 1 elements using 8 bytes
Name of the variable
Size of the variable
Type of variable (String, double)
• Variables are stored in the
workspace
MATLAB BASICS
18
18. Variables and Workspace
» clear a
» who
»
• Variables are stored in the
workspace
Variable list
MATLAB BASICS
19
19. Variables and Workspace
» a = 8;
» save tmp a
»
• Variables can be saved in files.
Semicolon suppresses output
File name Variable list (separate with spaces)
MATLAB BASICS
20
20. Variables and Workspace
» a = 8;
» save tmp a
» clear
» who
» load tmp
» who
Your variables are:
a
• Variables can be saved in files.
MATLAB BASICS
21
21. MATLAB BASICS
Common types of MATLAB variables
double: 64-bit double-precision floating-point numbers
They can hold real, imaginary or complex numbers in the
range from ±10-308 to ±10308 with 15 or 16 decimal digits.
>> var = 1 + i ;
char: 16-bit values, each representing a single character
The char arrays are used to hold character strings.
>> comment = ‘This is a character string’ ;
The type of data assigned to a variable determines the type
of variable that is created.
MATLAB BASICS
22
22. MATLAB BASICS23
Initializing Variables in Assignment
Statements
An assignment statement has the general form
var = expression
Examples:
>> var = 40 * i; >> a2 = [0 1+8];
>> var2 = var / 5; >> b2 = [a2(2) 7 a];
>> array = [1 2 3 4]; >> c2(2,3) = 5;
>> x = 1; y = 2; >> d2 = [1 2];
>> a = [3.4]; >> d2(4) = 4;
>> b = [1.0 2.0 3.0 4.0];
>> c = [1.0; 2.0; 3.0];
>> d = [1, 2, 3; 4, 5, 6]; ‘;’ semicolon
suppresses the
>> e = [1, 2, 3
4, 5, 6]; automatic echoing of values
but It slows down the execution.
23. MATLAB BASICS
27
Initializing with Keyboard Input
• The input function displays a prompt string in
the Command Window and then waits for the
user to respond.
my_val = input( ‘Enter an input value: ’ );
in1 = input( ‘Enter data: ’ );
in2 = input( ‘Enter data: ’ ,`s`);
MATLAB BASICS
24. MATLAB BASICS
28
Subarrays
• The end function: When used in an array
subscript, it returns the highest value taken on
by that subscript.
arr3 = [1 2 3 4 5 6 7 8];
arr3(5:end) is the array [5 6 7 8]
arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
arr4(2:end, 2:end)
MATLAB BASICS
25. MATLAB BASICS
29
Subarrays
• Assigning a Scalar to a Subarray: A scalar value
on the right-hand side of an assignment
statement is copied into every element specified
on the left-hand side.
>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
>> arr4(1:2, 1:2) = 1
arr4 =
1 1 3 4
1 1 7 8
9 10 11 12
MATLAB BASICS
26. MATLAB BASICS
30
Special Values
• MATLAB includes a number of predefined special values.
These values can be used at any time without initializing
them.
• These predefined values are stored in ordinary variables.
They can be overwritten or modified by a user.
• If a new value is assigned to one of these variables, then
that new value will replace the default one in all later
calculations.
>> circ1 = 2 * pi * 10;
>> pi = 3;
>> circ2 = 2 * pi * 10;
Never change the values of predefined variables.
MATLAB BASICS
27. MATLAB BASICS
31
Special Values
• pi: value up to 15 significant digits
• i, j: sqrt(-1)
• Inf: infinity (such as division by 0)
• NaN: Not-a-Number (division of zero by zero)
• clock: current date and time in the form of a 6-
element row vector containing the year,
month, day, hour, minute, and second
• date: current date as a string such as 16-Feb-
2004
• eps: epsilon is the smallest difference between
two numbers
• ans: stores the result of an expression
28. MATLAB BASICS32
>> prompt
. . . continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a
matrix
: specify range
29. MATLAB BASICS
33
Changing the data format
>> value = 12.345678901234567;
format short 12.3457
format long 12.34567890123457
format short e 1.2346e+001
format long e
1.234567890123457e+001
format short g 12.346
format long g
12.3456789012346
format rat 1000/81
MATLAB BASICS
30. MATLAB BASICS
The disp( array ) function
>> disp( 'Hello' )
Hello
>> disp(5)
5
>> disp( [ 'Bilkent ' 'University' ] )
Bilkent University
>> name = 'Alper';
>> disp( [ 'Hello ' name ] )
Hello Alper
MATLAB BASICS34
32. MATLAB BASICS
The fprintf( format, data ) function
– %d integer
– %f floating point format
– %e exponential format
– %g either floating point or
exponential format, whichever is
shorter
– n new line character
– t tab character
MATLAB BASICS36
33. >> fprintf( 'Result is %d', 3 )
Result is 3
>> fprintf( 'Area of a circle with radius %d is %f',
3, pi*3^2 )
Area of a circle with radius 3 is 28.274334
>> x = 5;
>> fprintf( 'x = %3d', x )
x = 5
>> x = pi;
>> fprintf( 'x = %0.2f', x )
x = 3.14
>> fprintf( 'x = %6.2f', x )
x = 3.14
>> fprintf( 'x = %dny = %dn', 3, 13 )
x = 3
y = 13
MATLAB BASICS37
34. MATLAB BASICS
• variable_name = expression;
– addition a + b a + b
– subtraction a - b a - b
– multiplication a x b a * b
– division a / b a / b
– exponent ab a ^ b
MATLAB BASICS38
35. Hierarchy of operations
• x = 3 * 2 + 6 / 2
• Processing order of operations is
important
– parentheses (starting from the innermost)
– exponentials (from left to right)
– multiplications and divisions (from left to
right)
– additions and subtractions (from left to
right)
>> x = 3 * 2 + 6 / 2
x =
9
MATLAB BASICS39
36. Built-in MATLAB Functions
• result = function_name( input );
– abs, sign
– log, log10, log2
– exp
– sqrt
– sin, cos, tan
– asin, acos, atan
– max, min
– round, floor, ceil, fix
– mod, rem
• help elfun help for elementary math
functions
MATLAB BASICS40
37. • Information is stored in
variables.
» a = [1 2 3; 4 5 6]
a =
1 2 3
4 5 6
Matrices
MATLAB BASICS
41
38. • Information is stored in
variables.
» a = [1 2 3
4 5 6]
a =
1 2 3
4 5 6
Matrices
[Enter]
MATLAB BASICS
42
48. MATLAB Relational Operators
MATLAB supports six relational operators.
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
MATLAB BASICS
52
49. MATLAB Logical Operators
MATLAB supports three logical operators.
not ~ % highest precedence
and & % equal precedence with or
or | % equal precedence with and
MATLAB BASICS
53
50. MATLAB Logical Functions
MATLAB also supports some logical functions.
xor (exclusive or) Ex: xor (a, b)
Where a and b are logical expressions. The xor operator
evaluates to true if and only if one expression is true
and the other is false. True is returned as 1, false as 0.
any (x) returns 1 if any element of x is nonzero
all (x) returns 1 if all elements of x are nonzero
isnan (x) returns 1 at each NaN in x
isinf (x) returns 1 at each infinity in x
finite (x) returns 1 at each finite value in x
MATLAB BASICS
54
54. • Element-by-element
operations
c = a*a
c = a(1,1) * a(1,1) ...
» a = [1 5; 6 9];
» c = a^2
c =
31 50
60 111
» c = a.^2
c =
1 25
36 81
MATLAB BASICS
58
55. • Elementary mathematical
functions
abs Absolute value
sqrt Square root
real Real part
imag Imaginary part
exp Exponential base e
log Natural logarithm
sin, cos, tan Trigonometric functions
MATLAB BASICS
59
56. • Elementary mathematical functions
sin, cos, tan Trigonometric functions
round Round to the nearest integer
fix Round toward zero
floor Round toward -Inf
ceil Round toward +Inf
MATLAB BASICS
60
60. Extracting a Sub-Matrix
A portion of a matrix can be extracted and
stored in a smaller matrix by specifying the
names of both matrices and the rows and
columns to extract. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 )
;
where r1 and r2 specify the beginning and
ending rows and c1 and c2 specify the
beginning and ending columns to be extracted
to make the new matrix.
MATLAB BASICS
64
64. MATLAB BASICS68
Flow Control Constructs
Logic Control:
IF / ELSEIF / ELSE
SWITCH / CASE / OTHERWISE
Iterative Loops:
FOR
WHILE
65. Control Structures
If Statement Syntax
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
MATLAB BASICS69
Some Dummy Examples
if ((a>3) & (b==5))
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end
66. If statement
EX (1):
If a<0
disp (‘a is negative’);
end
EX (2):
If x<0
error (‘x is negative; sqrt(x) is imaginary’);
else
r=sqrt(x);
end
EX(3):
If x>0
disp(‘x is positive’);
elseif x<0
disp (‘x is negative’);
else
disp (‘x is exactly zero’);
end
MATLAB BASICS70
67. MATLAB BASICS71
Switch, Case, and Otherwise
switch input_num
case -1
input_str = 'minus one';
case 0
input_str = 'zero';
case 1
input_str = 'plus one';
case {-10,10}
input_str = '+/- ten';
otherwise
input_str = 'other value';
end
Switch statement syntax:
Switch expression
case value1
Matlab Commands
case value2
Matlab Commands
.
.
.
otherwise,
Matlab Commands
end
68. Difference between if, and switch
More efficient than elseif statements
Only the first matching case is
executed
MATLAB BASICS72
69. Control Structures
For loop syntax
for i=Index_Array
Matlab Commands
end
MATLAB BASICS73
Some Dummy Examples
for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
70. For loop
Example: Sum of elements in a vector
X=1:5; %create a row vector
Sumx=0; %initialize the sum
For k=1:length(x)
sumx=sumx+x(k);
end
Example: A loop with non-integer increments
For x=0:pi/15:pi
fprintf(‘%8.2f %8.5fn’,x,sin(x));
end
MATLAB BASICS74
71. Control Structures
While Loop Syntax
while (condition)
Matlab Commands
end
MATLAB BASICS75
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
77. Graphics in MATLAB
• 2D Plotting commands
plot General 2D plots
xlabel, ylabel Axis labels
title Title of the figure
text Text in the figure
gtext Text in the figure (Mouse
input)
MATLAB BASICS
82
78. Matlab Graphs
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')
MATLAB BASICS83
79. Graphics in MATLAB
• 2D Plots
» x = [0.1:0.1:20]; y = [x.^3];
» plot (x,y)
» title ('This is the title')
» xlabel ('Label on X axis')
» ylabel ('Label on Y axis')
» grid
MATLAB BASICS
84