0% found this document useful (0 votes)
11 views

BME1901 Week 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

BME1901 Week 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Welcome to BME1901

Introductory Computer Sciences


2024-2025 Fall

Introductory Computer Sciences 2023-2024


1
Fall Week #2
• Instructor: Dr. Görkem SERBES (C317)
[email protected]
https://avesis.yildiz.edu.tr/gserbes/
• Assistants:
Fatih Ekrem ONAT - [email protected]
Beyza GÜL - [email protected]

• Grading:
• Midterm exam 30%
• Project 30%
• Final exam 40%

only individual submissions allowed!

Introductory Computer Sciences 2023-2024


2
Fall Week #1
BUILT-IN MATHEMATICAL
FUNCTIONS in MATLAB

Introductory Computer Sciences 2023-2024


3
Fall Week #2
Elementary math functions
The matrices A and B are defined as A = [1,2,3], B = [1,2,3;4,5,6;7,8,9] for the following
examples. If the input is a matrix, func() treats the columns of the matrix as vectors,
returning a row vector of the sums of each column.

Function Description Example


sum(A) = 6
sum() Sum of array elements sum(B) = [12,15,18]
prod(A) = 6
prod() Product of array elements prod(B) = [28,80,162]
max(A) = 3
max() Largest elements in array max(B) = [7,8,9]
min(A) = 1
min() Smallest elements in array min(B) = [1,2,3]
mean(A) = 2
mean() Average or mean value of array mean(B) = [4,5,6]

Introductory Computer Sciences 2023-2024


4
Fall Week #2
Elementary math functions ctd.
Function Description Example
returns an m-by-n matrix, containing
pseudorandom values drawn from the
rand(m,n)
standard uniform distribution on the
open interval (0,1)

round() Round to nearest integer round([1.5,-1.4]) = [2,-1]

floor() Round toward negative infinity floor([1.5,-1.4]) = [1,-2]

ceil() Round toward positive infinity ceil([1.5,-1.4]) = [2,-1]

fix() Round toward zero fix([1.5,-1.4]) = [1,-1]

mod(x,y) Modulus after division mod(3,2) = 1, mod(3,-2) = -1

rem(x,y) Remainder after division rem(3,2) = 1, rem(3,-2) = 1

Introductory Computer Sciences 2023-2024


5
Fall Week #2
Elementary math functions ctd.
Function Description Example
factorial() Factorial function factorial(5) = 120

perms() All possible permutations perms([3,5]) = [5,3;3,5]

factor() Prime factors factor(15) = [3,5]

primes(7) =
primes() Generate list of prime numbers [2,3,5,7]
Array elements that are prime
isprime() isprime([6,7]) = [0,1]
numbers

lcm() Least common multiple lcm(30,20) = 60

gcd() Greatest common divisor gcd(30,20) = 10

Introductory Computer Sciences 2023-2024


6
Fall Week #2
Complex number functions
Function Description Example
a+bi Complex number input in the x = 3+5i
a+bj command line x = 3+5j
Construct complex data from
complex() complex(a,b) = a+bi
real and imaginary components
Absolute value and complex
abs() abs(3+4i) = 5
magnitude
Phase angle of the complex
angle() angle(3+4i) = 0.9273
number

conj() Complex conjugate conj(3+5i) = 3-5i

Introductory Computer Sciences 2023-2024


7
Fall Week #2
Complex number functions ctd

Function Description Example


real() Real part of complex number real(3+5i) = 3
Imaginary part of complex
imag() imag(3+5i) = 5
number
x = 3+5i
isreal() Check if input is real array isreal(x) = 0
isreal(x+conj(x))=1
Signum function

sign() sign(3+4i)=0.6+0.8i
-

Introductory Computer Sciences 2023-2024


8
Fall Week #2
Trigonometric functions
• sine, cosine, tangent, cotangent, secant and cosecant functions are defined in
MATLAB as sin(), cos(), tan(), cot(), sec(), csc(), respectively for inputs in radians.

• Each trig function can be used for the inputs in degrees by adding “d” at the
end of the function.
Example: sind(90)=1.

• “h” is added to the end of a function for hyperbolic functions.


Example : sinh(1)=1.1752.

• “a” is added to the beginning of a function for inverse trigonometric functions.


Example: acos(1)=0.

Introductory Computer Sciences 2023-2024


9
Fall Week #2
Exponential functions
Function Description Example
sqrt(4) = 2
sqrt() Square root sqrt([1,4]) = [1,2]

exp() Exponential exp(1) = 2.718281828459046

Compute exp(x)-1 accurately for


expm1(x)
small values of x
nextpow2(8) = 3
p=nextpow2(A) gives the value
nextpow2() nextpow2(9) = 4
of p where 2p > A

Introductory Computer Sciences 2023-2024


10
Fall Week #2
Exponential functions ctd.
Function Description Example
log() Natural logarithm log(exp(2)) = 2

log10() Common (base 10) logarithm log10(100) = 2

log2() Base 2 logarithm log2(4) = 2

Compute log(1+x) accurately for


log1p(x)
small values of x
a = exp(2);
Natural logarithm for
reallog() reallog([a,a^2])=[2,4]
nonnegative real arrays

Introductory Computer Sciences 2023-2024


11
Fall Week #2
Polynomial functions
• An n-degree polynomial with constant coefficients (ai) is defined as,

• Polynomials are defined as row vectors in MATLAB, i.e.

p1=[1,2,3]; p2 = [2,3,4]; are considered to be defined for the examples given in


this subsection.

Function Description Example


roots(p1) =
roots() Polynomial roots [-1+1.4142i,-1-1.4142i]

polyval(p,x) Polynomial evaluation polyval(p1,[3,5]) = [18,38]

Introductory Computer Sciences 2023-2024


12
Fall Week #2
Polynomial functions ctd.
Function Description Example
Convolution and polynomial conv(p1,p2) =
conv()
multiplication [2,7,16,17,12]

deconv() Deconvolution and polynomial division deconv(p1,p2) = 0.5

If A is an n-by-n matrix, returns an n+1


element row vector whose elements are
the coefficients of the characteristic
poly(A) polynomial (det(sI-A)). If A is a vector,
returns a row vector whose elements are
the coefficients of the polynomial whose
roots are the elements of A.
polyder() Polynomial derivative polyder(p2) = [4,3]

Returns a polynomial representing the


polyint(p,k) integral of polynomial p, using a scalar polyint(p2,0) = [0.666,1.5,4,0]
constant of integration k.

Introductory Computer Sciences 2023-2024


13
Fall Week #2
Matrix operation functions
v = [1,2,3], A = [1,2,3;4,5,6;7,8,10] are considered to be defined for the examples given
in this subsection.
Function Description Example
returns mxn matrix of zeros where m
zeros(m,n) zeros(2,2) = [0,0;0,0]
and n are integers
returns mxn matrix of zeros where m
ones(m,n) ones(2,2) = [1,1;1,1]
and n are integers
eye(n) returns nxn identity matrix eye(2) = [1,0;0,1]

When x is a vector of n components,


returns a square matrix with the diag(A) = [1,5,10]
elements of x on the diagonal. When
diag(x) diag(v) =
x is a matrix, returns a column vector [1,0,0;0,2,0;0,0,3]
formed from the elements of the
diagonal of x.
det() Matrix determinant det(A) = -3

Introductory Computer Sciences 2023-2024


14
Fall Week #2
Matrix operation functions ctd.
Function Description Example
inv() Matrix inverse
norm(v,1) = 6,
norm() Vector and matrix norms norm(v,2) = 3.7417
null(A) =
null() Null space Empty matrix: 3-by-0

rank() Rank of matrix rank(A) = 3

rref() Reduced row echelon form

trace() Sum of diagonal elements trace(A)=16

X = sqrtm(A) →
sqrtm() Matrix square root X*X = A

Introductory Computer Sciences 2023-2024


15
Fall Week #2
Matrix operation functions ctd.
Function Description Example
eig() [w,D]=eig(X) produces matrices of [w,D]=eig(A)

eigenvalues (D) and eigenvectors w=


(V) of matrix X -0.2235 -0.8658 0.2783
-0.5039 0.0857 -0.8318
-0.8343 0.4929 0.4802

D=

16.7075 0 0
0 -0.9057 0
0 0 0.1982

expm(A) Matrix exponential

linsolve(A,B) Solve the linear system A*x=B

Introductory Computer Sciences 2023-2024


16
Fall Week #2
Linear system example
Let
3x 1+ 5x 2+ x3 = 16
x 1+ x2 = 3
+ 3x 2+ 5x 3 = 21
The solution to that linear system can be obtained in MATLAB as given below.

>> A = [3,5,1;1,1,0;0,3,5];
>> B = [16;3;21];
>> linsolve(A,B)

ans =

1.0000
2.0000
3.0000
Introductory Computer Sciences 2023-2024
17
Fall Week #2
Linear systems
4𝑥 + 5𝑦 = 6
3𝑥 − 2𝑦 = 14

Introductory Computer Sciences 2023-2024


18
Fall Week #2
Overdetermined Equations
4𝑥 + 5𝑦 = 6
3𝑥 − 2𝑦 = 14
7𝑥 + 2𝑦 = 19

Introductory Computer Sciences 2023-2024


19
Fall Week #2
Histogram in Matlab
• hist(x) (or histogram(x) in recent versions)
creates a histogram bar chart of the elements in
vector x.
• The elements in x are sorted into 10 equally
spaced bins along the x-axis between the
minimum and maximum values of x.
• hist displays bins as rectangles, such that the
height of each rectangle indicates the number of
elements in the bin.
• Important Note:
hist is not recommended. Use histogram instead in recent versions
of Matlab.

Introductory Computer Sciences 2023-2024


20
Fall Week #2
Histogram in Matlab
x = [0 2 9 2 5 8 7 3 1 9 4 3 5 8 10 0 1 2 9 5 10];
hist(x)

Introductory Computer Sciences 2023-2024


21
Fall Week #2
find function

Introductory Computer Sciences 2023-2024


22
Fall Week #2
Element-Wise Functions

Introductory Computer Sciences 2023-2024


23
Fall Week #2
Operators: element-wise

Introductory Computer Sciences 2023-2024


24
Fall Week #2
Operators: standard

Introductory Computer Sciences 2023-2024


25
Fall Week #2
M-FILES, USER-DEFINED INPUT
and OUTPUT

Introductory Computer Sciences 2023-2024


26
Fall Week #2
m-files
• Useful utilities translated into MATLAB (either sequences of command lines or
functions) and saved as m-files in the working directory are our primary goals.
• In the working directory, we will begin to accumulate a set of m-files that we
have created as you use MATLAB.
• The goals in designing a software tool are that it works, it can easily be read
and understood, and, hence, it can be systematically modified when required.
• For programs to work well they must satisfy the requirements associated with
the problem or class of problems they are intended to solve.
• The program must be readable and hence clearly understandable. Thus, it is
useful to decompose major tasks (or the main program) into subtasks (or
subprograms) that do specific parts of it. It is much easier to read subprograms,
which have fewer lines, than one large main program that doesn’t segregate
the subtasks effectively, particularly if the problem to be solved is relatively
complicated.

Introductory Computer Sciences 2023-2024


27
Fall Week #2
MATLAB Editor
• Example: a = 1;b = 2;c = 3;sum = a+b+c;

Introductory Computer Sciences 2023-2024


28
Fall Week #2
Running m-files
• In addition to save&run button in MATLAB editor, m-files can also be run as
depicted in the figures below.

Introductory Computer Sciences 2023-2024


29
Fall Week #2
Error handling & debugging

>> %%%%%%%% Example

a = 1; % value of a
b = 2; % value of b
c = 3; % value of c

sum = a b + c; % result
??? sum = a b + c; % result
|
Error: Unexpected MATLAB expression.

Introductory Computer Sciences 2023-2024


30
Fall Week #2
User defined input
• “input” function displays a text string in the command window and then waits
for the user to provide the requested input. The input value can then be used in
subsequent calculations

>> x = input('enter a value: ')


enter a value: 14
x=
14
• The same approach can be used to enter a one- or two-dimensional matrix. The
user must provide the appropriate brackets and delimiters.

>> x = input('enter the input vector: ')


enter the input vector: [1,2,3]
x=
1 2 3

Introductory Computer Sciences 2023-2024


31
Fall Week #2
Output options
• There are several ways to display the contents of an output.
• The general rule of displaying the result is scaled fixed-point format, with 4
digits after the decimal point.
• In MATLAB, format function controls the output format of numeric values
displayed in the Command Window.
Function Description Example (π)
Scaled fixed-point format, with 4 digits after the
format short (default) 3.1416
decimal point
Scaled fixed-point format, with 15 digits after the
format long 3.14159265358979
decimal point for double
Floating-point format, with 4 (15) digits after the 3.1416e+000
format shortE (longE)
decimal point for double 3.141592653589793e+000

Fixed- or floating-point, whichever is more


3.1416
format shortG (longG) readable, with 4 (15) digits after the decimal point 3.14159265358979
for double
format rat Ratio of small integers. 355/113

Introductory Computer Sciences 2023-2024


32
Fall Week #2
Output options ctd.
• “disp()” displays an array, without printing the array name. If the
input contains a text string, the string is displayed.
• The fprintf function (formatted print function) gives you even more
control over the output than you have with the disp() function. In
addition to displaying both text and matrix values, you can specify
the format to be used in displaying the values, and you can specify
when to skip to a new line.
• The general form of the fprintf command contains two arguments,
one a string and the other a list of variables:
fprintf(format-string, var,…)

Introductory Computer Sciences 2023-2024


33
Fall Week #2
Output options ctd.
• Consider the following example:
>> x = 5;
>> fprintf('The value of x is %f \n', x);
The value of x is 5.000000
>>

• The string, which is the first argument inside the fprintf function,
contains a placeholder (%) where the value of the variable (in this
case, x) will be inserted. The placeholder also contains formatting
information (see next slide).
• “\n” causes MATLAB to start a new line, we need to use \n, called a
linefeed, at the end of the string.

Introductory Computer Sciences 2023-2024


34
Fall Week #2
Output options ctd.
Other special format commands used for “fprintf” are listed in the table below

Format Description
%d Base 10 values
%e Exponential notation (3.141593e+00)
%f Fixed-point notation
%g The more compact of %e or %f, with no trailing zeros
%E Same as %e, but uppercase (3.141593E+00)
%G The more compact of %E or %f, with no trailing zeros
%c Single character
%s String of characters
%o Base 8 (octal)
%u Base 10
%x Base 16 (hexadecimal), lowercase letters
%X Same as %x, uppercase letters

Introductory Computer Sciences 2023-2024


35
Fall Week #2
Examples
>> B = [8.8 7.7 ; ... >> a = [1 9 23];
8800 7700]; >> fprintf('%u\n', a);
fprintf('X is %f meters or %f mm\n', 9.9, 9900, B) 1
9
X is 9.900000 meters or 9900.000000 mm 23
X is 8.800000 meters or 8800.000000 mm >> fprintf('%o\n', a);
X is 7.700000 meters or 7700.000000 mm 1
11
>> a = [1.02 3.04 5.06]; 27
fprintf('%d\n', a); >> fprintf('%x\n', a);
1.020000e+000 1
3.040000e+000 9
5.060000e+000 17
>> x = [2 987654321]; The value of x: 2.000000e+000
>> fprintf('x'' in degeri: %f \n',x) The value of x: 9.876543e+008
x' in degeri: 2.000000 >> fprintf('The value of x: %g \n',x)
x' in degeri: 987654321.000000 The value of x: 2
>> fprintf(‘The value of x: %e \n',x) The value of x: 9.87654e+008
Introductory Computer Sciences 2023-2024
36
Fall Week #2

You might also like