Lecture 3
Bu lt- n matr x funct ons,
Read ng data from f les
Bu lt- n Matr x Funct ons
Matlab Funct on Descr pt on
Determines the maximum value/values in x.
x is function argument (parameter).
max (x)
If x is vector, the answer is a scalar value.
If x is matrix, answer is vector conta n ng max mum of each column.
Returns the largest value in vector x, to var able a.
[a b] = max (x) Optionally b is the index locat on where the largest occurs.
If x is matrix, returns largest value in each column, to vector a.
max (x, y) Returns a matrix full of the larger of the two values in x and y.
m n (x) Determines the smallest value in x.
sum (x) Calculates the sum of elements in x.
prod (x) Calculates the product (multiplication) of elements in x.
Returns a vector with values of x, in ascending order (default).
sort (x)
If x is matrix, sort returns columns in ascending order.
sort (x, 'descend') Sorts n decreasing order.
Returns the r-by-c matrix into B matrix, whose elements are taken
B = reshape (A, r, c)
column-wise from A matrix.
2
Example : sum of vector
When the argument of sum funct on s a vector, then the
result w ll be a scalar (s ngle value).
>> a = [10 20 30 40 50];
>> sum(a)
ans =
150
Example : sum of matr x
When the argument of sum funct on s a matr x, then the result w ll be a vector.
By default, the sum funct on works columnw se (totals of each column
separately).
>> a = [10 20 30;
40 50 60;
70 80 90] Overall Total of matr x
>> sum(sum(a))
ans =
>> sum(a) Totals of each 450
ans = column
120 150 180
>> sum(a, 2)
Totals of each row
ans =
(Parameter 2 means
60 roww se sum)
150
240 4
Example : cumsum Funct on
When argument s a vector, cumsum funct on returns a vector of
cumulat ve sums.
When argument s a matr x, funct on returns a vector of
cumulat ve sums for each column.
>> a = [10 20 30 40 50]; >> a=[10 20 30;
40 50 60;
70 80 90]
>> cumsum(a)
ans =
10 30 60 100 150 >> cumsum(a)
ans =
10 20 30
50 70 90
>> sum(a) 120 150 180
ans =
150
Example : max Funct on
In examples below, X s a vector.
The max funct on returns only one scalar result by default.
>> X = [40 90 50 90 20]; We can d rectly g ve vector datas as
parameter.
>> max(X)
>> max( [40 90 50 90 20] )
ans =
ans =
90 90
>> [eb ind] = max(X)
In follow ng example, eb s the max mum value, eb =
and nd s the ndex locat on of max mum. 90
When there are more than one max mum (two 90’s),
Matlab returns the f rst element ndex. ind =
2
6
Example : mean Funct on
Mean funct on returns the average of elements n a vector
(or averages n a matr x).
>> mean( [10 40 15] )
ans =
21.6667
Examples w th Matr x
c = [1 3 7 ;
2 8 4 ;
6 -1 -2];
>> min(c)
ans = Returns m n mum of each column
1 -1 -2
>> min(c, [], 2)
ans =
Returns m n mum of each row
1
(Parameter 2 means roww se operat on)
2
-2
>> mean(c)
ans = Returns average of each column
3.0000 3.3333 3.0000
8
Example : Matr x Sort ng
The default d mens on s columnw se, and the default order ng s the
ncreas ng order.
Sort ng does not mod fy the or g nal matr x.
It only generates a sorted new copy of the matr x.
>> c = [1 3 7 ;
2 8 4 ;
6 -1 -2];
Sorts each column
>> sort(c) separately
ans =
1 -1 -2
2 3 4
6 8 7
General syntax of Sort funct on
Y = sort (X, DIM, MODE)
X s vector or matr x that w ll be sorted.
DIM and MODE are optional parameters.
Y is sorted result, which has same d mens ons as X.
DIM selects a dimension along which to sort.
1 means columnw se sort ng (default)
2 means roww se sort ng.
MODE selects the direction of sort.
'ascend' results in ascending order (default).
'descend' results in descending order.
10
Examples : Matr x sort ng
>> sort(c, 'descend')
>> c = [1 3 7 ; ans =
2 8 4 ; 6 8 7
6 -1 -2]; 2 3 4
1 -1 -2
Sorts each column separately n decreas ng order
>> sort(c, 2)
ans =
Sorts each row separately n ncreas ng order
1 3 7
(2 means roww se sort)
2 4 8
-2 -1 6
>> sort(c, 2, 'descend')
ans =
Sorts each row separately n
7 3 1 decreas ng order
8 4 2
6 -1 -2
11
Matr x row sort ng as groups : sortrows funct on
The sortrows funct on sorts rows of an matr x as groups n ascend ng order.
B = sortrows (A) sorts the rows of the matr x A n ascend ng order as a group.
B s the sorted result matr x w th the same s ze as A.
B = sortrows (A, COL) sorts A based on the columns spec f ed n the vector COL.
If an element of COL s pos t ve, the correspond ng column n A w ll be sorted n
ascend ng order.
f an element of COL s negat ve, the correspond ng column n A w ll be sorted n
descend ng order.
Example : sortrows (A, [2 -3] ) sorts the rows of A f rst n ascend ng order for the
second column, and then by descend ng order for the th rd column.
>> c = [1 3 7 ;
2 8 4 ;
6 -1 -2];
>> sortrows(c, [3])
ans = Sorts the rows as groups
6 -1 -2 of c matr x for the column 3,
2 8 4 n ascend ng order.
1 3 7
12
Example : reshape Funct on
The reshape funct on bu lds a new matr x.
Number of elements n A and B are the same.
Elements are collected columnw se.
>> A=[10 20 30 40 ;
50 60 70 80 ;
90 100 110 120]
>> B = reshape(A, 6, 2)
B =
10 30
50 70
90 110
20 40
60 80
100 120
13
Example : Calculat ng Sum of Taylor Ser es
The following is formula of Taylor series , for calculating cos(x).
Wr te a Matlab program to read N (number of terms) from user,
then calculate Taylor ser es sum.
Test your program for X=150 degree.
Calculate the actual result (factual) by us ng the bu lt- n cos(X) funct on.
Calculate the truncat on error.
Absolute d fference between Taylor sum and the actual value s called the truncat on error.
Truncat on error = | factual ─ fsum |
14
Matlab Program
% The program uses Taylor series to calculate cos(x) func on.
clc; clear;
N = input ('Terim sayisini (N) veriniz :');
degree = 150;
X = degree*pi/180;
% Degree is converted to Radian
k = [0 : N]; % Vector
terim = (-1).^k .* X.^(2*k) ./ factorial(2*k) ;
fsum = sum( terim )
factual = cos(X)
truncation_error = abs(factual – fsum)
15
Screen outputs
Test ng w th N=3 Test ng w th N=20
Terim sayisini (N) veriniz : 3 Terim sayisini (N) veriniz : 20
fsum = fsum =
-0.9168 -0.8660
factual = factual =
-0.8660 -0.8660
truncation_error = truncation_error =
0.0508 0
Number of terms (N) determ nes
the accuracy of result.
16
Stat st cal Funct ons
Matlab
Descr pt on
Funct on
mean (x) Calculates the average of elements n vector x.
var (x) Calculates the var ance of x vector.
std (x) Calculates the standard dev at on of x vector.
mad (x) Calculates the mean absolute dev at on of x vector.
X (x x)
N N
2
Mean ( x ) 1 Var ance 1
N N
Standard dev at on Var ance
x x
N
Mean absolute dev at on 1
N
17
Example: Stat st cal Funct ons
Veriler = [92 62 70 51];
Ortalama = mean (Veriler)
Varyans = var (Veriler)
Standart_dev = std (Veriler)
Mutlak_dev = mad (Veriler)
Ortalama =
68.7500
Varyans =
Screen 300.9167
output
Standart_dev =
17.3469
Mutlak_dev =
12.2500
18
Random number generat ng funct on: rand
Matlab
Descr pt on
Funct on
Generates nxn square matr x w th randomly
generated double (fract onal) data numbers.
rand (n) Range of generated random numbers are
between 0.0 to 1.0
rand (n, m) Generates nxm matr x w th random data.
>> rand (3) >> round ( rand (3) * 100 )
ans = ans =
0.3500 0.6160 0.8308 60 69 8
0.1966 0.4733 0.5853 26 75 23
0.2511 0.3517 0.5497 65 45 91
>> rand (1, 3) >> round ( rand (1, 3) * 100 )
ans = ans =
0.9172 0.2813 0.7572 92 28 76
19
Methods of
Read ng Data
from F les
20
Methods of Read ng Data from F les
Method1: load funct on
Read nto a matr x
Method2: textread funct on
• Read nto parallel vectors
• Alternat ve: Read nto a structure
21
Method1 : load Funct on
When the data f le conta ns only numbers, the eas est method s the load funct on.
EXAMPLE: Each row n f le conta ns data about a c rcle.
• x coord nate of center
• y coord nate of center
• rad us c rcles.txt F le
3 4 20
The follow ng command reads all data into a 1 1 2
matrix, w th the same name of f le (c rcles). 7 5 10
>> load('circles.txt') 3 9 8
3 8 6
The follow ng command reads data into a matrix
that named d fferently (da reler). 4 9 6
>> daireler = load('circles.txt') 1 6 3
5 5 12
4 4 15
22
Access ng Matr x Columns
load ('circles.txt')
x = circles (: , 1) c rcles s a matr x, loaded from f le.
y = circles (: , 2) x, y, r are column vectors.
r = circles (: , 3)
Column 1 Column 2 Column 3
x = y = r =
3 4 20
1 1 2
7 5 10
3 9 8
3 8 6
4 9 6
23
Method2 : textread Funct on
• When data f le conta ns d fferent types of data n columns
(such as str ngs and numbers), the load funct on can not be used.
• Instead, the textread funct on should be used.
• Example: Read entire file into three column vectors.
>> [ogrnum, isim, notu] = textread ('students.txt', '%d %s %d' );
Vectors File name Format specifiers
d is decimal number
s is string
• First %d is for ogrnum
• Second %d is for notu
• %s is for isim
24
Example Data F le : students.txt
Each row conta ns data about a student: 111 AAA 78
• ogrnum 222 BBB 85
• sm 333 CCC 89
• notu 444 DDD 94
555 EEE 86
ogrnum = sm= notu =
Workspace 78
111 'AAA'
(Three column 85
222 'BBB'
vectors) 333 'CCC' 89
444 'DDD' 94
86
555 'EEE'
25
Access ng tems from column vectors
Gett ng f elds from column vectors, for student at ndex 1.
>> ogrnum(1) >> isim(1) >> notu(1)
ans = ans = ans =
'AAA'
111 78
Gett ng f elds from column vectors, for student at ndex 2.
>> ogrnum(2) >> isim(2) >> notu(2)
ans = ans = ans =
'BBB'
222 85
26
Import ng Data from
Spreadsheet F le
(M crosoft Excel, etc.)
nto MATLAB
27
Prepar ng CSV F le n Excel
• Open the Excel program and enter data values.
• From the F le menu, choose Save As.
• Select the CSV (Comma Separated Values) format.
28
Import ng CSV F le nto Matlab
• In Matlab, select the Current Folder.
• R ght-cl ck on the source f le name (c rcles.csv).
• Cl ck the Import Data command.
c rcles.csv F le
x;y;r
3;4;20
1;1;2
7;5;10
3;9;8
3;8;6
4;9;6
1;6;3
5;5;12
4;4;15
29
Import ng CSV F le nto Matlab
• Matlab opens the Import w ndow.
• Select the mport ng cho ce (Column vectors or Matr x)
• Cl ck the Import Select on command.
30
Import ng CSV F le nto Matlab
• After the mport ng, the Matlab Workspace conta ns the data values.
• Depend ng on the user select on, data w ll be n column vectors,
or n one matr x.
31