2-Programming in MATLAB
2-Programming in MATLAB
Development in MATLAB
THE PROGRAM DESIGN PROCESS
Step 1 Problem analysis
The context of the proposed investigation must be established to provide the proper motivation for
the design of a computer program. The designer must fully recognize the need and must develop an
understanding of the nature of the problem to be solved.
Step 2 Problem statement.
Develop a detailed statement of the mathematical problem to be solved with a computer program.
Step 3 Processing scheme.
Define the inputs required and the outputs to be produced by the program.
Step 4 Algorithm.
Design the step-by-step procedure in a top-down process that decomposes the overall problem into
subordinate problems. The subtasks to solve the latter are refined by designing an itemized list of
steps to be programmed. This list of tasks is the structure plan and is written in pseudo-code (i.e., a
combination of English, mathematics, and anticipated MATLAB commands). The goal is a plan that is
understandable and easily translated into a computer language.
Step 5 Program algorithm.
Translate or convert the algorithm into a computer language (e.g., MATLAB) and debug the syntax
errors until the tool executes successfully.
Step 6 Evaluation.
Test all of the options and conduct a validation study of the program. For example, compare results
with other programs that do similar tasks, compare with experimental data if appropriate, and
compare with theoretical predictions based on theoretical methodology related to
Step 7 Application.
Solve the problems the program was designed to solve. If the program is well designed and useful, it
can be saved in your working directory (i.e., in your user-developed toolbox) for future use.
Programming MATLAB Functions
GENERAL-PURPOSE COMMANDS Controlling the Command Window
demo Run demos clc Clear Command Window
help Online help echo Echo commands in script
helpwin Display categories of format Set output format for disp
functions with links to each category home Send cursor home
lookfor Keyword search through help more Control paged output
entries
type List M-files Interactive input
what Directory listing of M- and MAT- input Prompt user for input
files keyboard Invoke keyboard as script
which Locate functions and files file
Managing variables and the menu Generate menu of choices for
workspace user input
clear Clear variables and functions pause
MATRICESWait for user response
from memory eye Identity matrix
disp Display matrix or text linspace Vector with linearly spaced
length Length of vector elements
load Retrieve variables from disk ones Matrix of ones
save Save workspace variables to rand Uniformly distributed random
disk numbers and arrays
size Array dimensions randn Normally distributed random
who, whos List variables in numbers and arrays
workspace zeros Matrix of zeros
… and more in Appendix C : (colon) Vector with regularly spaced
elements
Example 1
Compute the perimeter p and the area A of a
triangle whose sides are a, b, and c
Example 2: The projectile problem
calculate the flight of a projectile (e.g., a golf ball)
launched at a prescribed speed v and a prescribed
launch angle
Inline objects
y = x3 + 3x2 – 4
x = -4: +4
Basic vector
Row vector
c = [7 8 9 10 11]
Column vector
c = [7; 8; 9; 10; 11]
Transpose of a vector t_r = r’
Appending of a vector r = [r1, r2] r = [r1; r2]
Operations
Addition
Subtraction
Multiplication M = r .* c
Division D = r ./ c
Bài tập
Tạo 2 vector từ ngày tháng năm sinh của sv theo cú
pháp
[DD MM]
[YY YY]
e.g. a(3,2)
a(2:3, 1:2)
Transpose
a = [1:3; 4:6]
b = a’
Colon operator
a(1:2,2:3) = ones(2)
a (:, 2:3) = ones(3)
a (2:end,2:3) = zeros(2)
Bài tập
Giải hệ phương trình bằng pp ma trận
2 𝑥+ 𝑦 + 𝑧=13
𝑥 −2 𝑦 + 𝑧=2
𝑥 − 𝑦 +4 𝑧=7
Matrices and Arrays
Duplicating rows and columns
1 2 3
a =[1 2 3] 1 2 3
1 2 3
repmat(a, [3 1])
100
I = eye (3) 010
001
Zeros, Ones matrices
I = ones (3) I = ones (3, 1)
I = zeros (3) I = zeros (1, 3)
Random matrices
R = rand (3) R = randint (3) R = randi ([min max] [m,n])
R = rand (3,5)R = randint (2, 3)
Manipulating matrices
C = A .* B ?
Matrix Exponentiation
A ^ 2 = A*A
Other Matrix Functions
det determinant. A = [2 4 1 ; 6 7 2 ; 3 5
9]
det(A) = -77
rank rank of a matrix rank(A)
trace Trace of a matrix trace(A)
sum Sum elements in column Sum(A)
eig eigenvalue decomposition.
expm matrix exponential (eA) Expm(A)
inv Inverse a matrix Inv(A)
lu LU factorization (into lower [L, U] = lu(A)
and upper triangular
matrices).
A = L*U
qr orthogonal factorization. [Q, R] = qr(A)
A = Q*R; Q*Q’ = I
svd singular value
decomposition.
Example
Using LU matrix
Example
Linear Equations
3x +2y − z = 10
−x +3y +2z = 5
x − y − z=−1
3 2 −1 x 10
A −1 3 2 X y B 5
1 −1 −1 z -1
A.X = B
X = A-1.B or A \ B
Exercise
Do exercise 6.3
Exercise (e-learning)
Logical Vector
When a vector is involved in a logical expression,
the comparison is carried out element by element
(as in an arithmetic operation). If the comparison is
true for a particular element of the vector, the
resulting vector, which is called a logical vector, has
a 1 in the corresponding position; otherwise it has a
0. r = 1:5; 11100
r <= 3
Logical Vector
a = 1:5;
b = [0 2 3 5 6]; 01100
a == b
Logical Vector: Examples
Discontinuous graph
x = 0 : pi/20 : 3 * pi;
y(x) =
y = sin(x);
Over the range of [0: 3π]
y = y .* (y > 0); % set negative values of sin(x) to
plot(x, y)
Logical Vector: Examples
Avoiding division by zero
r = rand(1,7)
sum( r < 0.5 )
Logical Operators
Logical Operators and Vectors
Examine
~(~[1 2 0 -4 0])
x = x + (x == 0)*eps; x = x + (~x)*eps;
Logical Operators and Vectors
Exercise
~a
a&b
a|b
? xor(a, b)
a = [-1 0 3]; a>0&b>0
b = [0 3 1]; a>0|b>0
~a>0
a + (~ b)
a>~b
~a>b
~ (a > b)
Logical Vectors
Subscripting
a = [-2 0 1 5 9];
a([5 1 3])
returns
9 -2 1
a(logical([0 1 0 1 0]))
Logical Functions
Functions Return
any(x) 1 (true) if any element
of x is non-zero (true)
all(x) 1 if all the elements of x
are non-zero
exist(‘a’) 1 if a is a workspace
variable
find(x) a vector containing the
subscripts of the non-
zero (true) elements of x
isempty(x) 1 if x is an empty array
and 0 otherwise
isinf(x) 1’s for the elements of x
which are +Inf or −Inf,
and 0’s
Otherwise
isnan(x) 1’s where the elements
of x are NaN and 0’s
E.g.
a = [-4 0 5 -3 0 3 7 -1 6]
if all(a >= 1)
do something
end
if any(a ~= b)
statement
end
Exercise
Exercise
5.1,
5.2,
5.3,
5.4
Loop
for
while
Importing and Exporting Data
Exporting text (ASCII) and binary data
A = [1 2 3; 4 5 6]
Exporting image
Image show
image (IMG)
imshow (IMG)
Bài tập
Tìm trên Internet 1 hình ảnh trắng – đen (lưu file
vào máy tính)
Đọc file ảnh này vào Matlab
Xuất hình ảnh ra màn hình
Thay đổi giá trị của các pixcel [0,0], [10,10], [20,20]
Ghi ảnh đã thay đổi vào 1 file khác
Xuất ảnh đã thay đổi ra màn hình và so sánh với
hình ảnh gốc
Function M-files: General form
Keyword Return values Inputs
r = rand(100,1);
[a, s] = stats(r);
Function M-files: basic rules
function keyword
Input and output arguments
Multiple output arguments
Naming convention for functions
Help text
Local & Global variables: scope
Persistent variables
remain in existence between function calls.
Vector arguments
Checking the number of function arguments
nargin and nargout
Viết hàm giải pt bậc 2 (theo kiểu MATLAB)
Trong đó kiểm tra số lượng tham số đầu vào hợp lệ
(bằng 3)
Sử dụng biến nargin
Subfunction
A function M-file may contain the code for more
than one function.
function [avg, med] = newstats(u) % Primary function
% NEWSTATS Find mean and median with internal functions.
n = length(u);
avg = mean(u, n);
med = median(u, n);
end end
P-code files
You can use the p-code function to save the parsed
version of an M-file for use in later MATLAB
sessions,
Function handles
handle = @sqrt;function y = myFunction(x) function y =
eval(fhandle, 9) y = sin(x) + cos(x); computeSquare(x)
eval(fhandle, 25)end y = x.^2;
end
f = @myFunction;
q = integral(f,0,2*pi); f = @computeSquare;
R = feval(f, pi/2); a = 4;
b = f(a)
= @(x) exp(-x.^2).*log(x).^2
Q = integral(f,0,Inf)
figure;
h2 = plot(x, y2) ;
n! = n×(n− 1)!
function y = fact(n)
% FACT Recursive definition of n!
if n > 1
y = n * fact(n-1);
else
y = 1;
end;
Exercise
Use M-function for Newton method to calculate
square root
1. Initialize a
2. Initialize x to a/2
3. Repeat n = 10 times (say) the following:
Replace x by (x +a/x)/2
Display x
4. Stop
Doing exercises
7.5;
7.7
Debugging M-files
Debugging a script and function
Set a breakpoint
Debug: Run (F5)
Step (F10)
Step-in (F11): take into the function
Exercise
7.5
7.7
7.8