Matlab Tutorial - CIE323 - 2018
Matlab Tutorial - CIE323 - 2018
University at Buffalo
MATLAB Tutorial
Dr. Amjad Aref
1
Introduction
- MATLAB is a software package for doing numerical computations. Its name is
derived from MATrix LABoratory.
- Variable names must start with a letter and can be followed by letters, digits
and underscores. Variables are case sensitive.
>> x = 2;
>> abc_123 = 0.005;
>> 1ab = 2;
Error: Unexpected MATLAB expression.
- Some special variables:
pi ‐‐‐Value of π
inf ‐‐‐ Infinity
NaN ‐‐‐Not a number e.g. 0/0
- Relational operators:
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
- Logical operators:
not ~
and &
or |
2
Matrices
- MATLAB treats all variables as matrices. Vectors are special forms of matrices
with only one column OR one row. Scalars are matrices with only one row and
one column.
- Creating a scalar:
>> x = 10;
,
- Creating a row vector: “Use ”
>> a = [1,5,‐8]
a =
1 5 ‐8
- Creating a column vector: “Use ” ;
>> a = [1;5;‐8]
a = 1
5
‐8
- Creating a matrix:
>> a = [1,2,3;8,8,9;6,5,1]
a =
1 2 3
8 8 9
6 5 1
- Matrix Addition (+):
3
- Matrix Multiplication (*):
- Matrix Element Wise operation
- Matrix Manipulation functions
4
- Elementary Math functions
5
Graphics
- 2D Plotting (Example1)
Sample Plot
1
0.8
0.6
0.4
0.2
Y values
-0.2
-0.4
-0.6
Sine(x)
-0.8 Cosine(x)
-1
0 1 2 3 4 5 6 7
X values
6
- 2D Plotting (Example2)
0.9
0.8
0.7
0.6
y values
0.5
0.4
0.3
0.2
0.1
0
0 1 2 3 4 5 6
t values
7
- Subplots
8
Import and Export of Data
- Basic Input‐Output Functions
- Read/Write from a text file
9
Loop and Logical Statements
- ‘for’ Loop: Repeats a statement for a specific number of times
- General form of ‘for’ statement:
- Example1:
- Example2:
10
- ‘if’ statement
- General form:
- Example 1:
- Example 2:
11
- ‘while’ loop
- General form:
- Example 1:
- Example2:
12
Function
- General form
function [y1,...,yN] = myfun(x1,...,xM)
- Save the function code in a text file with a .m extension.
- The name of the file should match the name of the first function in the file
- Valid function names begin with an alphabetic character, and can contain
letters, numbers, or underscores.
- Example1: Function with one output
- Example2: Function with Multiple outputs
13