Introduction to MATLAB
Faculty of Information Technology
Palestine Technical University “Kadoorie”
Abeer Qashou
Variables and Assignment Statements
No need for types. i.e.,
int a;
double b;
float c;
All variables are created with double precision unless
specified and they are matrices.
Example:
>>x=5;
>>x1=2;
After these statements, the variables are 1x1 matrices
with double precision
Variables
To store a value in MATLAB, a variable is used.
The Workspace Window shows variables that have been
created.
The format of an assignment statement is:
Variablename = expression
Note that the variable name must always be on the left, and the expression on the right
Variables
The rules for Variable Names and File Names
The name must begin with a letter of the alphabet (e.g., A2z or a2z )
MATLAB is case-sensitive, which means there is a difference between
upper and lowercase letters.
There are certain words called reserved words can not be used as
variable names.
Names of built-in functions can not be used as variable names.
up to 63 characters
can be a mix of letters, digits, and underscores (e.g., vector_A)
Cannot contain punctuation characters (e.g. period, comma, semicolon)
No spaces are allowed between characters (use the underscore where a
space is desired)
Variables
Assignment statement:
Variable = number;
Variable = expression;
Example:
>> tutorial = 1234;
>> tutorial = 1234
NOTE: when a semi-colon
tutorial = ”;” is placed at the end of
1234 each command, the result
is not displayed.
Variables Names
MATLAB variables are defined by assignment. There is
no need to declare in advance the variables that we
want to use or their type.
Example
x=1; % Define the scalar variable x
y=[1 2 3] % row vector
z=[1;2;3] % column vector
A=[1 2 3;4 5 6;7 8 9] % 3x3 matrix
whos % List of the variables defined
Note: terminate statement with semicolon (;) to suppress
output.
Predefined Variables and Keywords
There are seventeen words, called keywords, that are
reserved by MATLAB for various purposes, and cannot
be used as variable names. These words are:
break case catch continue else elseif
end for function global if otherwise
persistent return switch try while
Variables
Special variables:
ans : default variable name for the result
pi: = 3.1415926…………
eps: = 2.2204e-016, smallest amount by which 2 numbers can differ.
Inf or inf : , infinity
NaN or nan: not-a-number
i Defined as , which is: 0 + 1.0000i (Imaginary unit(
j Same as i.
Commands involving variables:
who: lists the names of defined variables
whos: lists the names and sizes of defined variables
clear: clears all variables, reset the default values of special variables.
clear name: clears the variable name
clc: clears the command window
clf: clears the current figure and the graph window.
Workspace Command
The Workspace Window shows that variables that
have been created in the current command
window and their values. The following commands
relate to variables:
Variables
MATLAB uses a default variable named ans
if an expression is typed at the prompt and it
is not assigned to a variable.
For example, the result of the expression 6 + 3
is stored in the variable ans
Data Types in MATLAB
In MATLAB, data types (also called classes)
define the type of values a variable can store
and determine the operations that can be
performed on them. MATLAB provides various
built-in data types, categorized into
1. Numeric
2. Character
3. Logical
4. Structured
5. special types.
Numeric Data Types
Store numerical values and are the most
commonly used data types in MATLAB
It includes three (3) sub types:
1. Floating- Point Numbers
2. Integers
3. Complex Numbers
Floating Point
These are the default number types in MATLAB,
used for real and complex numbers.
1. Double: (Default Numeric Type):
64-bit floating-point numbers (high precision).
Supports real and complex numbers.
is more precise but uses more memory.
Floating Point
2. Single:
32-bit floating-point numbers.
is faster and memory-efficient (less memory
usage) but less precise.
Note: You can check the type of any variable using
class (variable)
Integers
MATLAB provides signed and unsigned integer
types.
Examples
8-bit signed integer
• 8-bit unsigned integer
Summary
Every expression, or variable, has a type
associated with it.
MATLAB supports many types, which are
called classes
Complex Numbers
MATLAB supports complex numbers with
real and imaginary parts using i or j
Character and String Data Types
1- Character Arrays (Char)
Used for storing text as a sequence of
characters.
Enclosed in single quotes (' ').
Character and String Data Types
String Arrays (String).
Enclosed in double quotes (" ").
Allows easy string manipulation.
Character and Encoding
Logical Data Type (Boolean)
Stores true (1) or false (0) values.
Used for conditional operations and logical
indexing.
Structured Data Types
1- Cell Arrays (Cell)
Can store different data types and sizes in the
same array.
A cell array is a data type with indexed data
containers called cells, where each cell can
contain any type of data
Uses {} curly braces
Structured Data Types
2- Structures (Struct)
Stores data in named
fields, similar to objects in
OOP.
Arrays with named fields that can contain data
of various types and sizes
A structure array is a data type that encloses related data
using data containers called fields. Each field can contain any
type of data. Data in a structure is accessed using dot
notation of the form structName.fieldName
Syntax
s = struct
s = struct(field,value)
s = struct(field1,value1,...,fieldN,valueN)
s = struct([])
Structured Data Types
3- Tables (table): Array in tabular form whose named columns
can be of different types.
Used for organizing tabular data like spreadsheets
a data type suitable for column-oriented or tabular data
often stored as columns in a text file or spreadsheet.
Each variable in a table can have a different data type and
size, with the only restriction being that each variable must
have the same number of rows
>>
t=table (["ali";"sara"], [22;24], [90; 85], 'VariableNames', ["name","age", "grade"])
Names = {'Ahmed'; 'Sara'; 'Ali'};
Ages = [25; 30; 22];
Genders = {'Male'; 'Female'; 'Male'};
T = table(Names, Ages, Genders);
disp(T);
Data Types Conversion
MATLAB allows converting data from one
type to another using built-in functions.
Function Converts to Example
double(x) Double-precision number x = double(5);
single(x) Single-precision number y = single(3.14);
int8(x), int16(x), Integer types z = int16(100);
int32(x), int64(x)
uint8(x), uint16(x), Unsigned integers a = uint8(255);
uint32(x), uint64(x)
char(x) Converts numeric values to b = char(65);
characters % returns 'A'
logical(x) Converts numbers to true c = logical(0);
(nonzero) or false (zero) % returns false
int2str(x) v = int2str(22);
Convert integers to characters
% v=‘22’
mat2str(x) Convert matrix to characters m = mat2str([3.84 2.81; 6.74
9.99]);
% m= ‘[3.84 2.81; 6.74 9.99]’
num2str(x) Convert numbers to character n = num2str(3.98); %n=‘3.98’
array
str2double(x) converts from string to double- st= str2double('4.5534')
precision value %st=4.5534
str2num(x) Convert character array or string t = str2num('24');
to numeric array % t=24
base2dec(x) converts from base N number ba = '1A';
string to decimal number x = base2dec(ba,12);
% x = 22
dec2base(x) converts from decimal to base N number = 22;
number in string. deb = dec2base(number,12);
% deb = ‘1A’
x = base2dec('1101', 2);
% x = 13
y = dec2base(13, 2);
% y = '1101'
x = base2dec('27', 8);
% x = 23
y = dec2base(23, 8);
% y = '27'
y = dec2base(45, 10);
% y = '45'
x = base2dec('1F', 16);
% x = 31
y = dec2base(31, 16);
% y = '1F'
Operations in MATLAB
Operation is defined as an action performed on data (such
as numbers or matrices) to achieve a specific result, like
performing a calculation, comparison, or modifying the data.
Operations can be classified into different types, such as:
Arithmetic Operations.
Logical Operations.
Relational Operations.
Others (Set operations, Bit-Wise operations, Special Characters)
Arithmetic Operations in MATLAB
These operations are used to perform basic mathematical
calculations like addition, subtraction, multiplication, division, and
more.
Here are some of the common operations that can be used
with numerical expressions:
Operation Symbol Example Answer
Addition + 5+3 8
Subtraction - 5-3 2
(negation)
Multiplication * 5*3 15
Division / 10/5 2
(divided by)
Division \ 5\10 2
(divided into)
Exponentiation ^ 5^2 25
(Power)
Numbers can also be shown usin
scientific or exponential notation
Arithmetic (Math) Operation Precedence
Note: For nested parentheses, the innermost are executed first.
Examples
Examples
Some Math Constants
Relational Operations
To compare two values or expressions to determine the
relationship between them, such as equality, greater than,
less than, etc.
When two numbers are compared, the result is 1 (logical
true) if the comparison, according to the relational operator,
is true, and 0 (logical false) if the comparison is false.
Relational operators in MATLAB
Operation Symbol Definition Example Answer
Equal to == Compares whether two values are 5==3 0 (false)
equal
Not Equal to ~= Compares whether two values are not 5~=3 1 (true)
equal.
Less than < Compares if the left operand is less a = 6; 0 (false)
than the right operand b = 4;
result = (a < b);
Greater than > Compares if the left operand is greater a = 10; 0 (false)
than the right operand. b = 15;
result = (a > b);
Less than or <= Compares if the left operand is less a = 6; 1 (true)
than or equal to the right operand. b = 6;
equal to
result = (a >= b)
Greater than or >= Compares if the left operand is greater a = 4; 1 (true)
than or equal to the right operand. b = 7;
equal to
result = (a <= b);
Examples
Examples
Logical Operations
An operation that works with Boolean values (true or false,
represented as 1 or 0). These operations are used to
evaluate logical conditions and make decisions in programs.
Logical operators have numbers as operands. A nonzero
number is true, and a zero number is false.
Logical operators (like relational operators) are used as
arithmetic operators within a mathematical expression.
Examples
Cond1 | cond2 Cond1 & cond2 Cond2 Cond1
T T T T
T F F T
T F T F
F F F F
Order of precedence
Arithmetic, relational, and logical operators
can all be combined in mathematical
expressions.
When an expression has such a combination,
the result depends on the order in which the
operations are carried out.
Precedence Operation
1 (highest) Parentheses (If nested parentheses exist, inner have precedence).
2 Exponentiation.
3 Logical NOT (~).
4 Multiplication, division.
5 Addition, subtraction.
6 Relational operators (>, <, >=, <=, ==, ~=).
7 Logical AND (&).
8 (lowest) Logical OR ( | ).
Scalars, Vectors, and Matrices
A scalar is a single number (one element).
Example:
Scalars are also treated as arrays by
MATLAB (1 row and 1 column).
Scalars, Vectors, and Matrices
A vector is a list of numbers (one row or
one column).
It is an array with one dimension (One-
Dimensional Array)
Scalars, Vectors, and Matrices
A matrix is a table of numbers (rows ×
columns).
It is a Two-Dimensional Array (Array with
more than one dimension).
Thank You…