BSM510 Numerical Analysis - mohaisen.net · Introduction and Matlab Fundamentals Korea University...
Transcript of BSM510 Numerical Analysis - mohaisen.net · Introduction and Matlab Fundamentals Korea University...
Introduction and Matlab Fundamentals
Korea University of Technology and Education (KUT)
BSM510
Numerical Analysis
Manar Mohaisen
Department of EEC Engineering
Lecture Content
Introduction to MATLAB
2Korea University of Technology and Education (KUT)
Introduction to MATLAB
MATLAB
3Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Scalars♦ >> x = 5;
x 5
♦ >> y = sin(pi/4);
x 0.7071
♦ >> z = power(2, 5); % 2 to power 5
z 32
♦ >> data = 5/2 + 5;
data 7.5
♦ >> d = 5 + j3;
d 5 + sqrt(-1)*3
♦ d = d / 2;
d 2.5 + j1.5
♦ >> scale = sqrt(sin(0.5*pi*real(d)));
scale sqrt(sin(3/4*pi)) = i0.8409
4Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Vectors♦ >> x = [1 3 5];
x is a row vector of size 13
♦ >> y = x.^2; % y[i] = x[i]*x[i]
y [1 9 25]
♦ >> p = sum(y);
p is the total power of x
♦ >> vec = x.’; % transpose operator
vec is a column vector = [1 3 5]T
♦ >> q = [5, 3, -1.1]; % equivalent to [5 3 -1.1]
q is a row vector of size 13
♦ >> v = [-9; 4; 16];
v is a column vector of size 31
♦ >> sr = sqrt(v);
sr [3i; 2; 4], with i = sqrt(-1)
5Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Vectors – contd.♦ >> re = [7 3 2 -1].’;
♦ >> im = [1 3 1 0].’;
♦ >> co = re + sqrt(-1)*im;
co [7+i 3+i3 2+i -1]T;
♦ coCT = co.’; % transpose
coT = [7+i 3+i3 2+i -1]
♦ coRT = co’; % conjugate transpose
coT = [7-i 3-i3 2-i -1]
♦ >> mul = re.*im; % element-wise multiplication
mul = [7; 9; 2; 0]
♦ >> div = 7*im./re;
div = [1; 7; 3.5; 0]
♦ >> une = ones(1, 5); zero = zeros(1, 4);
une [1 1 1 1 1]; zero = [0 0 0 0];
6Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Vectors – contd.♦ >> index = 1:2:9;
index [1 3 5 7 9]
♦ >> range = 5:-0.5:3;
range [5 4.5 4 3.5 3]
♦ >> a = [1 -1 5 3]; b = [0.5 3 5 2];
♦ >> y = a*b.’; % vector multiplication
y 28.5
♦ >> z = a*b;
Wrong: inner matrix dimensions must agree
♦ >> x = a(1, 1:2); w = [a(1) a(3) a(2)]; z=a(4:-1:1);
x [1 -1]; w [1 5 -1]; z = [3 5 -1 1];
♦ >> v1 = max(a); v2 = min(a); v3 = var(a);
♦ >> v4 = mod(b, 2);
v4 [0.5 1 1 0]
7Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Vectors – contd.♦ >> x = [1 5 3 -1];
♦ >> Y = diag(x);
♦ >> q = prod(x); % product of the elements of x
q = -15
♦ >> y = find(x >= 2); % indices of elements >= 2
y [2 3]
>> num = prod(size(y)); % the number of elements >= 2
■ num 2
♦ >> y = [7 8 4 1];
>> m = [x y]; z = [x; y];
m [1 5 3 -1 7 8 4 1]
8Korea University of Technology and Education (KUT)
1 0 0 00 5 0 00 0 3 00 0 0 1
Y
1 5 3 17 8 4 1
z
Introduction to MATLAB - contd.
Vectors – example
♦ Plot the following function using commands in the command window
9Korea University of Technology and Education (KUT)
>> x = [-5:0.1:5]; % range of ind. variable
>> f = 1/sqrt(2*pi) * exp(-x.^2 ./ 2); % dependent variable
>> plot(x, f, ‘linewidth’, 1.5) % 2d plot
>> xlabel(‘x’)
>> ylabel(‘f(x)’)
>> grid on % add the grid to the figure
2/21( )2
xf x e
-5 -4 -3 -2 -1 0 1 2 3 4 50
0.1
0.2
0.3
0.4
x
f(x)
Introduction to MATLAB - contd.
Vectors – example
♦ Plot the following function in the range [-5, 5] with increment 0.05
10Korea University of Technology and Education (KUT)
2sin(2 )cos( )
1( ) x x
xf x
>> x = [-5:0.05:5]; % range of ind. variable
>> f = sin(2*pi*x).*cos(pi*x); % divide expression into 1
>> f = f./(x.^2 + 1); % and 2
>> plot(x, f, ‘linewidth’, 1.1) % 2d plot
>> axis([-5 5 -0.8 0.8]; %axis([xmin xmax ymin ymax])
>> xlabel(‘x’)
>> ylabel(‘f(x)’)
>> grid on % add the grid to the figure
-5 -4 -3 -2 -1 0 1 2 3 4 5
-0.5
0
0.5
x
f(x)
Introduction to MATLAB - contd.
Vectors – creating functions (m files)
♦ The function should have the following form
Programmed in the “edit window”, then it is called in the “command window” or in
other function or m file
Example 1
Example 2
11Korea University of Technology and Education (KUT)
function [list of outputs] = functionName(list of inputs)
% function’s body
%
function [val] = NormalF(x, a, b)
% returns the value of the pdf of gaussian RV at x
% a is the variance and b is the mean
%
Val = 1/sqrt(2*pi*a) * exp(-(x-b)^2 / (2*a) )
function [vecP] = vecPower(v)
% returns the total power of the vector v
v = v(:); % v becomes column vector
vecP = v’*v; % works for complex vectors as well
Introduction to MATLAB - contd.
Vectors – example 3
12Korea University of Technology and Education (KUT)
function [va vn] = acceleration(m, cd)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% inputs: m (kg)
% cd (kg/m)
% outputs: va analytical results
% vn numerical results
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
g = 9.81; % acceleration due to gravity
t = 0:0.5:12; % time range
va = sqrt(g*m/cd).*tanh(sqrt(g*cd/m).*t); % analytical velocity
vn = zeros(1, length(t)); % initiate numerical v to zero
for ii = 2 : 1 : length(t)
vn(ii) = vn(ii-1) + (g - cd/m*vn(ii-1)^2) * (t(ii)-t(ii-1));
end
plot(t, va, '-o') % plot the analytical results
hold % hold the plot to add other curve
plot(t, vn, 'r') % plot the numerical results
xlabel('time (s)'); % set the x label
ylabel('v (m/s)'); % set the y label
grid on % show the grid
0 2 4 6 8 10 120
10
20
30
40
50
60
time (s)
v (
m/s
)
analytical
numerical
Introduction to MATLAB - contd.
Vectors – random values
13Korea University of Technology and Education (KUT)
% Gaussian numbers
>> x = randn(1, 4); % Gaussian random values w. mean=0, var=1
>> y = randn(1, 4)+2; % Gaussian random values w. mean=2, var=1
>> z = 2*randn(1, 4)-2; % Gaussian random values w. mean=-2, var=4
>> w = (randn(1, 4) >= 0); % generates binary numbers with equal prob
% equal probability integers
>> x = randint(1, 4); % binary values
>> y = randint(1, 4, [-2 2]); % random int in [-2,2] (-2 -1 0 1 2)
% any real value with any probability
>> a = randsrc(1, 4, [1 3]); % random numbers 1 or 3 (same prob)
>> b = randsrc(1, 4, [1 3; 0.4 0.6]);% prob(1) = 0.4, prob(3) = 0.6
% real random numbers (uniform distribution)
>> g = rand(1, 4); % real numbers in [0, 1] with equal prob
>> h = rand(1, 4) – 0.5; % real numbers in [-0.5, 0.5] with equal prob
% try to check the help on those functions using the “help” command
>> help rand
Introduction to MATLAB - contd.
Matrices
♦ A vector is a special case of matrices that has either dimension = 1
All what we introduces about vectors still applied to matrices
♦ >> x = [2 4; 5 1] % 2x2 matrix, the ‘;’separates rows
♦ >> y = [5 1 7; 3 1 0]; % 2x3 matrix
♦ >> z = randn(5); % 5x5 matrix with N(0,1) entries
♦ >> w = diag(z); % 5x1 vector (diagonal elements of z)
♦ >> a = transpose(x); % same as x’ or x.’ for real
♦ >> u = inv(x); % inverse of x
♦ >> detX = det(x); % determinant
♦ >> traceX = trace(x); % trace of x
♦ >> vec = x(:, 1); % vec is the first column of x
♦ >> vec1 = x(2, :); % vec1 is the second row of x
♦ >> parY = y(:, 1:2); % parY = [5 1; 3 1]
♦ >> prodM = x*y; % matrix multiplication
14Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Matrices – contd.♦ >> x = [2 4; 5 1] % 2x2 matrix
♦ >> y = x.^2; % y = [4 16; 25 1]
♦ >> z = x^2; % z = x*x;
♦ >> U = trace(x’*x); % what is this?
♦ >> logV = log(x); % element-wise log (natural log)
♦ >> w = sqrtm(x); % w*w = x
♦ >> m = sqrt(x); % m(i,j) = sqrt(x(i, j)
♦ >> [a b] = size(x); % a=# of rows, b=#of columns
♦ >> n = prod(size(x)); % # of elements in x
♦ >> T = reshape(x, 1, 4); % T = [2 5 4 1]
♦ >> U = x(:, [2 1]); % exchange columns 1 and 2
♦ >> M = x*y; % #of col. in x = #of rows in y
♦ >> V = x.*y; % x and y are with same dimensions
♦ >> P = sum(sum(x.*x)); % total power of x
15Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
Input-output
♦ Input
>> x = input(‘display message’)
■ Example: n = input(‘enter your weight (kg): ‘)
♦ Output
>> disp(‘message to display’)
■ Example: disp(‘error, please try again!’)
>> fprintf(‘format’, values or variables);
■ Example: fprintf(‘your weight is %f kg’, 125.3);
■ Notes
» This functionality is same as printf in c
» fprintf can be used for both file/screen display in MATLAB
16Korea University of Technology and Education (KUT)
Introduction to MATLAB - contd.
If statement
Loops
17Korea University of Technology and Education (KUT)
if (condition 1)
statements
elseif (condition 2)
statements
else
statements
end
if (x > 0)
disp(‘x is positive)
elseif (x < 0)
disp(‘x is negative’)
else
disp(‘x = 0’)
end
for index = start:step:end
statements
end
y(1) = -5;
for ii = 2 : 1 : 100
y(ii) = y(ii-1) + ii^2
end
Example
Example
Introduction to MATLAB - contd.
Relational operators
Logical operators
18Korea University of Technology and Education (KUT)
== equal
~= not equal
< less than
> larger than
<=,>= less/larger than
~ not
& and
| or
Introduction to MATLAB - contd.
Anonymous functions
♦ Allows you to create a function without creating an M-file.
♦ Format: fhandle = @(list of args) expression
19Korea University of Technology and Education (KUT)
>> a = 5;
>> b = 3;
>> f1 = @(x,y) a*x^2 + b*y^2
>> f1(2, 3)
ans =
47
>> a = 10; % does not affect the result
>> f1(2, 3)
ans =
47
Introduction to MATLAB - contd.
Function functions
♦ A function that takes a function as an argument
♦ Example:
20Korea University of Technology and Education (KUT)
function favg = funcafvg(f, a, b, n)
% inputs: f is a function to be evaluated
% [a,b,n] interval limits and # of points
x = linspace(a, b, n);
Y = f(x);
favg = mean(y);
>> f1 = @(x) 5*x^2 + 3*x – 2;
>> funcavf(f1, 0, 12, 60);
M-file
Command window
Lecture Summary
We introduced an overview of MATLAB
21Korea University of Technology and Education (KUT)