You are on page 1of 21

Computer Programming

(CSC209)

Lecture (2)
MATLAB BASICS
Dr.Omar Almutairi
Arrays

 The fundamental unit of data in any


MATLAB program is the array.
 Arrays can be classified as either
vectors or matrices.
 The size of an array is specified by
the number of rows and the number
of columns in the array, with the
number of rows mentioned first.

2
Variables and Arrays
An array is a collection of data values organized into rows
and columns and known by a single name.

3
Data organized as Arrays

4
Complex and Constant Number
>> pi
ans =
Constant Number 3.1416
>> i
ans =
0.0000 + 1.0000i

>> y = 3 + 7i
y=
Complex 3.0000 + 7.0000i
>> x = 2*pi
x=
6.2832 5
Creating and Initializing Variables

• Three common ways to initialize a variable


in MATLAB
1. Assign data to the variable in an assignment
statement.
2. Input data into the variable from the keyboard.
3. Read data from a file.

6
Initializing Variables

7
Initializing Variables in Assignment Statements

• Don’t need to initialise type, or dimensions


>>A = [3 2 1; 5 1 0; 2 1 7]
square brackets to define matrices
A=
semicolon for next row in matrix
3 2 1
5 1 0
2 1 7
>>
8
Manipulating Matrices
• Access elements of a matrix A=
3 2 1
>>A(1,2) 5 1 0
2 1 7
ans= indices of matrix element(s)
2
• Remember Matrix(row,column)
• Naming convention Matrix variables start
with a capital letter while vectors or scalar
variables start with a simple letter

9
Operator and matrices
>>A(3,2:3)
ans = A=
3 2 1
1 7
5 1 0
>>A(:,2)
2 1 7
ans =
2
1
1
What’ll happen if you type A(:,:) ?

10
Algebraic Operation
a = [0 1+7]; a = [0 8]
b = [a(2) 7 a]; b = [8 7 0 8]

c(2,3) = 5;

d = [1 2];
b = [1 2 0 4]
d(4) = 4;

11
The : Operator
>> x= 1:10
x=
1 2 3 4 5 6 7 8 9 10
>> x = 1:2:10
x=
1 3 5 7 9
>> x’
x=
1
3 Try the following
>> x=0:pi/12:2*pi;
5
>> y=sin(x)
7 12
9
Basic Function in MATLAB

• Built-In Function
• User Define function

13
Common list of Functions

Try the following


14
Initializing with Built-In Functions
a = zeros(2);
b = zeros(2,3);
c = [1 2; 3 4];
d = zeros(size(c));

a = ones(2)
b = ones(2,3)

15
User Define Function in MATLAB
• Similar to script files except that
– temporary variables remain local
– function use standardized input and
output parameters
• Script files good for quick and dirty jobs

16
More Usefull functions

17
Input keyboard

Example
%Losses = Total distance in kilometers * loss per
kilometer
x = input('Distance in kilometer = ');
losses = x*5

>> Untitled3
x = input('Distance in kilometer = ');
losses = x*5
Distance in kilometer = 6 18
losses = 6*5 = 30
Input keyboard
Entering multiple statements per line

>> a=7; b=cos(a), c=sin(a)


b=
0.7539
c=
0.6570

19
Practice & Quiz 2

20
END
21

You might also like