You are on page 1of 20

Lecture 2

Matr x Operat ons,


Bas c Input / Output

Matr ces
 A matrix is a two-dimensional array of data values.

 In Matlab, to refer to an entire matrix, the name of matr x s used without


subscripts. Example: D refers to whole matrix.

 Subscripts (indexes) are used to access a specified item (element).


 Row and column indexings begin from 1.
Example: D(3, 2) refers to row 3 and column 2, and gives 78.

 A matrix that contains n rows and m columns has a total of nxm values.
Example: D matrix contains 4x3 = 12 values.

-1 30 6
15 2 -7
D matrix -9 78 20
4 0 19
4x3
2
Def n ng Matr ces
 Each row of a matrix can be defined on a separate line.
 Data tems w th n a row can be separated by commas ( , ) or spaces.

B = [-1, 0, 1 ;
1, 2, 1 ;
3, 1, 2 ;
4, 0, 4 ];

 Long rows can be continued on the next line,


through the use of a comma and three dots.

F = [1, 52, 64, 97, 42, -36, ...


55, 82, 23, 104 ]

• Elements of a matrix can be changed individually,


by referring to a specific location (index).

K = [10, 60, 40] ;


K(2) = 30  Th s command changes value of K(2) from 60 to 30. 3
Example : L near Algebra Mult pl cat on
of Two Matr ces (In Matlab)
>> A = [5 8 0 ;
6 4 9];

>> B = [4 7 1 5 ;
2 0 3 4 ;
7 1 8 0];

>> C = A * B
Same results are
C = obtained with
36 35 29 57 manual calcula ons.
95 51 90 46
6
Examples : Matr x Operat ons
* Operator s used for normal matr x mult pl cat on.
(Us ng the l near algebra rules).
.* Operator s used for element-by-element mult pl cat on.
(Not us ng the l near algebra rules).

>> a = [1 2 3] Matr x mult pl cat on error:


a =
1 2 3 a is 1x3 matrix.
b is 1x3 matrix.
>> b = a + 5
a and b can not be multiplied,
b = according to the linear algebra rules.
6 7 8
Because dimensions of a and b are
>> c = a .* b not compatible.
c =
6 14 24 Linear Algebra Matrix multiplication
rule: Number of columns in a must be
>> d = a * b equal to Number of rows in b.
??? Error using ==> m mes
Inner matrix dimensions must agree.
7
Matrix Concatenation Operation
• We can define a new matrix by using previously defined other matrices.
• Concatenation works like cut&paste operation.

A = [5 6 4];

B = [ 3 A 2 ];  [3 5 6 4 2 ]

x = [1 2 3];
y = [7 9 4];

z = [x y];  [1 2 3 7 9 4]

u = [ x ; y]  1 2 3
7 9 4

Address ng the Matr x Elements


• General syntax for address ng ( ndex ng) an element of a matr x :

Matr x_name (row_ ndex , column_ ndex)

>> A = [1 2 3 ; 4 5 6 ; 7 8 9]
A = 1 2 3
4 5 6
7 8 9

>> A(2, 2) % Display the element n locat on (2, 2)


ans =
5

>> A(3, 2) = 0 % Change value of element n (3, 2)


A =
1 2 3
4 5 6
7 0 9
10
Colon Operator ( : )
 The colon ( : ) operator can be used to generate new vectors or matrices.
 For example, it can be used to generate new vectors from a matrix.
 When a colon operator is used in place of a specific subscript ( ndex) ,
the colon represents the entire row or column.

>> C = [10, 20, 30;


40, 50, 60;
70, 80, 90;
100, 110, 120]

x = C(: , 1); % copies first column of C, to column vector x.


y = C(: , 2); % second column copied
z = C(: , 3); % third column copied

x vector y vector z vector


10 20 30
40 50 60
70 80 90
100 110 120
11

Example1 : Colon operator


>> A = [1 2 3 ;
4 5 6 ;
7 8 9]

% Access ng rows and columns

>> A(2 , :) Gets all columns n row 2


ans =
4 5 6

>> A(: , 1) Gets all rows n column 1


ans =
1
4
7
12
Example2 : Colon operator
C = [1, 2, 5 ; -1, 0, 1 ; 3, 2, -1 ; 0, 1, 4]

Take all rows of C,


but only column 2 through column 3,
n each row.

F = C(: , 2:3)  [2, 5 ; 0, 1 ; 2, -1 ; 1, 4]

13

Example3 : Colon operator


C = [1, 2, 5 ; -1, 0, 1 ; 3, 2, -1 ; 0, 1, 4]

Take row 3 through row 4 of C,


column 1 through column 2, n each row.
The result s a reg onal copy.

G = C(3:4 , 1:2) [3, 2 ; 0, 1]

14
end keyword
>> A = [1 2 3 ; 4 5 6 ; 7 8 9]
A = 1 2 3
4 5 6
The end keyword 7 8 9
can be used as the Gets the
element n last
last index in an >> A(2, end) column of row 2
indexing expression. ans =
6
Gets the element
n last row of
>> A(end, 2) column 2
ans =
8
Gets the element n
>> A(end) last column and last row
ans =
9
Gets the elements
n last two columns
>> A(3, 2:end) of row 3
ans =
8 9
15

Vector zat on Operat on

 Data values in a matrix might be entered by hand one-by-one.


 But evenly spaced data values can be generated much more easily,
by using the vectorization operation.

 Usage of the column ( : ) operator for generat ng data values


s called as "vector zat on" .

 Vectorization Examples:
a = 1 : 5

a = [ 1 : 5 ]

Both commands return a row vector containing linear (vectoral) values.


[ 1 2 3 4 5 ]

16
General Form of Vector zat on
 General form of vector zat on:
Var ableName = StartValue : IncrementValue : EndValue

 The increment value is optional, its default value is 1.

>> a = 1 : 5
a =
1 2 3 4 5

>> a = 1 : 2 : 5
a =
1 3 5

>> a = 1 : 2 : 8
a =
1 3 5 7

17

Vector zat on Examples


Example: Pos t ve ncrement.
>> t = 0.0 : 0.5 : 2.5

t =
0 0.5 1.0 1.5 2.0 2.5

Example: Negat ve ncrement. (Also called as decrement.)


>> A = 10 : -1 : 2

A =
10 9 8 7 6 5 4 3 2

Example: Inval d ncrement value. Matlab g ves error.


>> A = 10: -2 : 50
A =

Empty matrix: 1-by-0


18
l nspace Funct on for Vector zat on
 linspace (a, b, n) gives n evenly (l nearly) spaced values between a and b.

variable = linspace (a, b, n)

 If the n argument s om tted, Matlab generates 100 values by default.

>> linspace(1, 5, 10)

ans =

Columns 1 through 8
1.0000 1.4444 1.8889 2.3333
2.7778 3.2222 3.6667 4.1111

Columns 9 through 10
4.5556 5.0000

19

Defining an Empty Matrix

 An empty matrix s def ned w th blank brackets [ ] ,


which does not contain any elements.
 An empty matrix is different from a matrix that contains only zeros.

>> a = []

a =
[]

20
Spec al Matr ces
Bu lt- n
Explanat on
Funct on name
zeros(n) Returns a n × n matrix of zeros

zeros(m, n) Returns a m × n matrix of zeros

ones(n) Returns a n × n matrix of ones

ones(m, n) Returns a m × n matrix of ones

For a m × n matrix A, returns the row vector [m,n] containing the


size(A)
number of rows and columns in matrix

length(A) Returns the larger of the number of rows or columns in A

Returns a n × n dent ty matr x, wh ch d agonal elements are 1,


eye(n)
other elements are zero.

21

Spec al Matr x Examples

>> C= [1 2 3; 4 2 5]; >> ones(3)*7


ans =
>> size(C) 7 7 7
ans = 7 7 7
2 3 7 7 7

22
Array Operations
 Element-by-element array operations can be performed one at a t me.

>> A = 10 : 10 : 50
A =
10 20 30 40 50

>> B = 20 : 10 : 60
B =
20 30 40 50 60

 Alternatively, we can also write


>> C(1) = A(1) * B(1);
the following short operation,
>> C(2) = A(2) * B(2);
>> C(3) = A(3) * B(3); which is equivalent to above
>> C(4) = A(4) * B(4); statements.
>> C(5) = A(5) * B(5);
>> C = A .* B

>> C C =
C = 200 600 1200 2000 3000
200 600 1200 2000 3000

23

Element-by-element Operat ons


(A s vector, s s scalar)

Matlab
Explanat on Form Example Result vector
Operator
Scalar add t on to
+ A+ s [4 , 6] + 3 [7 , 9]
array
Scalar subtract on
- A- s [4 , 6] - 3 [1 , 3]
from array
Scalar
* mult pl cat on of A* s [4 , 6] * 3 [12 , 18]
array
Scalar d v s on of
/ A/ s [4 , 6] / 2 [2 , 3]
array
Scalar
.^ exponent at on of A .^ s [2 , 5] .^ 3 [8 , 125]
array

24
Element-by-element Operat ons
(A and B are both vectors)
Matlab
Explanat on Form Example Result vector
Operator
Vectors
+ A+ B [4 , 6] + [8 , 1] [12 , 7]
add t on
Vectors
- A-B [4 , 6] – [8 , 1] [-4 , 5]
subtract on
Vectors
.* mult pl cat o A .* B [4 , 6] .* [8 , 1] [32 , 6]
n
Vectors r ght
d v s on
./ A ./ B [4 , 6] ./ [8 , 1] [0.5 , 6.0]
(normal
d v s on)
Vectors left
.\ A .\ B [4 , 6] .\ [8 , 1] [2.0 , 0.167]
d v s on
Vectors
.^ exponent at A .^ B [2 , 5] .^ [6 , 4] [64 , 625]
on
25

Example Problem
 Convert a l st of Degrees to Rad ans.
 Both * and .* operators can be used.
 For convers on, Degrees vector s mult pl ed by p , wh ch s a scalar value.

>> Degrees = [10 15 70 90];

>> Radians = Degrees * pi / 180

Radians =
0.1745 0.2618 1.2217 1.5708

>> Radians = Degrees .* pi / 180

Radians = Same
0.1745 0.2618 1.2217 1.5708 results

26
Example1: Matr x exponent (^) operator

>> a = [1 2 ; 3 4]
a =
1 2
3 4

>> a ^ 3

ans = a^3 means mult ply the matr x a by tself 3 t mes.


37 54
81 118 The matr x a must be square matr x.
(Row and column lengths must be same)

>> a * a * a 1 2 1 2 1 2
* *
3 4 3 4 3 4
ans =
37 54
81 118
27

Example2: Element-by-element
exponent (.^) operator

>> a = [1 2 ; 3 4]
a =
1 2
3 4

>> a .^ 3
a .^ 3 s means element-by-element power
ans = of each value n the matr x a.
1 8
27 64 13 23
33 43

28
Mult pl cat on of a Matr x
w th a Scalar Value

A = [ 1 : 4 ; -1 : -1 : -4 ; 3 1 2 -1 ]

B = A .* 5

B = A * 5 % Same result as above

A= B=

29

Vector Transpose and


Matr x Transpose
 The s ngle quote symbol ( ' ) s used as transpose operator.
 Transpose operator converts rows to columns, and columns to rows.

>> A = [10 20 30 40];


>> B = [5 10 15 20];

>> Tablo = [ A' , B' ]

Tablo =
10 5
20 10
30 15
40 20

>> Tablo'
ans =
10 20 30 40
5 10 15 20 30
Bas c Input/Output

31

User Input from Keyboard


 User can enter a scalar value, values of a vector, or values of a matrix,
through the keyboard by using the input command.
 Input command displays a text string as screen message,
then waits for the input entered by user.
 The values (data) are then stored in the variable specified.

clc; % Clear the command w ndow Screen output

a = input('Birinci sayıyı giriniz : Birinci sayıyı giriniz : 5


İkinci sayıyı giriniz : 4
');
b = input(‘İkinci sayıyı giriniz : '); Toplam :
c = a + b; 9

% Sonucu konsol ekranına yaz.


disp('Toplam : ');
disp(c);

32
User Input from Keyboard
 If more than one value is to be entered by user, user must separate values with
space or commas, and enclose all data with left and right brackets [ ].

>> A = input ('A vektörü için değerleri giriniz : ')

A vektörü için değerleri giriniz : [ 2 -5 6 4 7 ]

A =
2 -5 6 4 7

 If you are nputt ng a str ng, then you should wr te the 'S' letter
as spec f er n nput command.

>> isim = input ('Ad soyad giriniz : ', 'S')

Ad soyad giriniz : Aaa Bbbb


isim =
Aaa Bbbb
33

S mple d splay ng funct ons


 There are two Matlab funct ons to display text and the contents of a matrix.
 disp() function is used for simple output.
 fprintf() function is used for formatted output.

>> disp('Program başladı...')


Program başladı...

>> M = [1 2 ; 3 4];

>> disp(M)
1 2
3 4

34
Examples of d sp funct on
 The d sp funct on can d splay more than one var able.
 Us ng brackets [ ] allows only same type of var ables.
 If str ngs and numbers are wr tten n same l st, only the str ngs are d splayed.
 Us ng curly parantheses { } allows each tem as a separate vector.

>> a = 5; b = a^2; s1 = 'Apple'; s2 = 'Orange';

>> disp( [a b s1 s2] ) L st conta ns numbers and str ngs.


AppleOrange But only str ngs are d splayed.

>> disp( [a b] ) L st conta ns only numbers.


5 25

>> disp( [s1 ' ' s2] )


Apple Orange L st conta ns only str ngs.

>> disp( { a b s1 s2 } ) L st conta ns numbers and str ngs.


[5] [25] 'Apple' 'Orange' The { } symbols are cell array
paranthes s. 35

Formatted pr nt ng funct on
 fprintf() command can be used for formatted printing.
fprintf (format_string, variables)

 The format_string specifies how the values will be displayed.


 It must contain a format conversion code for each of the output variables.
 It can also contain any text characters.

 Format conversion codes:


%s String
%d Decimal integer with no fractional part
%f Floating-point value
%e Floating-point value in scientific notation
\n A newline in output string
\t A tab in output string

36
Us ng fpr ntf for scalar values

>> temp = 98.6;

>> fprintf('The temperature is %f degrees \n', temp)

The temperature is 98.600000 degrees

>> fprintf('The temperature is %.2f degrees \n', temp)

The temperature is 98.60 degrees

37

Us ng fpr ntf for matr ces


>> PuanTablosu = [ 1 2 3 4;
75 88 102 93;
99 84 95 105 ]

PuanTablosu =
1 2 3 4  F rst row represents Müsabaka numbers
75 88 102 93
 Second row represents scores of Takım1
Th rd row represents scores of Takım2
99 84 95 105

>> fprintf('Müsabaka %d , Takım1 %d , Takım2 %d \n', PuanTablosu)

Screen output: Müsabaka 1 , Takım1 75 , Takım2 99


fpr ntf always outputs Müsabaka 2 , Takım1 88 , Takım2 84
the transposed matr x Müsabaka 3 , Takım1 102 , Takım2 95
Müsabaka 4 , Takım1 93 , Takım2 105
38
The format Command

 You can use the format command n command w ndow to change the
d splay format of float and double numbers (fract onal).
 Default format s short.

>> Sayi = 12.345678901234567;

format short 12.3457


format short g  12.346
format short e 1.2346e+01

format long 12.34567890123457


format long g 12.3456789012346
format long e 1.234567890123457e+01

39

You might also like