Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

2-Programming in MATLAB

Uploaded by

huyphan1455
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

2-Programming in MATLAB

Uploaded by

huyphan1455
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Program Design and Algorithm

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

h(t) = cos(8t)+ cos(9t).

h = inline( ’cos(8*t) + cos(9*t)’ );


x = 0 : 20/300 : 20;
plot(x, h(x)), grid
 E.x

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]

 Thực hiện các phép toán


 Nối 2 vector thành 1 vector 1 chiều theo hàng
 Nối 2 vector thành 1 vector 2 chiều 2x2
 Cộng/Trừ vector 1 chiều với chính nó
 Nhân/Chia vector 1 chiều với chính nó
Matrices and Arrays
 Create a matrix
A = 1: 100;
A = [1:100];
a = [1 2; 3 4];
x = [5 6];
 Subscripts a = [a; x]
a(i,j)

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])

 Deleting rows and columns 1 2 3


1 2 3
a(1,:) = [ ]
a(:,2) = [ ] 1 3
1 3
 Re-shape an array 1 3
b = [1:100]
b = reshape(b, [10 10]) 1 2 3….
10
11 12 13
….20
…….
Matrices
 Elementary matrix (E):
 is an n x n matrix obtained from I matrix by one
elementary row operation 100 200
010 010
 Identity matrix 001 001
 may be used to construct a tridiagonal matrix

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

diag extracts or creates a diagonal.


fliplr flips from left to right.
flipu flips from top to bottom.
d
rot90 rotates.
tril extracts the lower triangular part
Matrix Operations
 Matrix multiplication
C=A*B 5 4
A = [1 2; 3 4] 15 14
B = [5 6; 0 -1]

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

x = -4*pi : pi/20 : 4*pi;


x = x + (x == 0)*eps; % adjust x = 0 to x = eps
Over the range [-4π : 4π]y = sin(x) ./ x;
plot(x, y)
Logical Vector: Examples
 Avoiding infinity
x = -3/2*pi : pi/100 : 3/2*pi; x = -3/2*pi : pi/100 : 3/2*pi;
y = tan(x); y = tan(x);
y = y .* (abs(y) < 1e10); % remove the big one
plot(x, y) plot(x, y)
Logical Vector: Examples
 Counting random numbers

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]

Text data: save myData.txt A –ascii

Binary data save myData

 Importing text (ASCII) data and binary data


Text data B = load(‘myData.txt’)

Binary data B = load myData


Importing and Exporting Data
 Exporting xls (or csv) data
STATUS = xlswrite (FILE,ARRAY,SHEET,RANGE)

% Write mixed text and numeric data to


testdata2.xls
% starting at cell E1 of Sheet1:
d = {'Time','Temperature'; 12,98; 13,99;
14,97};
 Importingxlswrite('testdata2.xls',
xls (or csv) data d, 1, 'E1')
[NUM,TXT,RAW,CUSTOM ]= xlsread (FILE,SHEET,RANGE)

% Read a specific range of data:


subsetA = xlsread('myExample.xls', 1, 'B2:C3')
Example
% Create data for use in the examples that follow:
values = {1, 2, 3 ; 4, 5, 'x' ; 7, 8, 9};
headers = {'First', 'Second', 'Third'};
xlswrite('myExample.xls', [headers; values]);
moreValues = rand(5);
xlswrite('myExample.xls', moreValues,
'MySheet');

% Read data from the first worksheet into a


numeric array:
A = xlsread('myExample.xls')

% Read a specific range of data:


subsetA = xlsread('myExample.xls', 1, 'B2:C3')

% Read from a named worksheet:


B = xlsread('myExample.xls', 'MySheet')
Exercise
 Tải “Grading.xlsx” từ e-learning
 Vẽ phổ điểm bằng MATLAB
Importing and Exporting Images
 Importing images
IMG = imread (FILENAME, FORMAT)

 E.g. myimage = imread(‘mypicture.jpg’);

 Exporting image

imwrite (A, [MAP], FILENAME)

 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

function [ outarg1, outarg2, . . .] = name( inarg1, inarg2, . . . )


% comments to be displayed with help
...
var 1;
var 2;
global var3;
outarg1 = ... ;
outarg2 = ... ;
end
Built-in Function

the trigonometric functions


sin, cos, tan, csc (i.e. cosec), sec, cot
and their inverse functions
asin, acos, atan, acsc, asec, acot
the hyperbolic functions
sinh, cosh, tanh, csch (i.e. cosech), sech,
coth
and their inverse functions
asinh, acosh, atanh, acsch, asech, acoth
User-defined function
 Create a function

function [y] = myfunc(x)


% where $x$ is the input and $y$ is the output.
y = x.^3 - 0.95*x;
end % This is not necessary to include;
however, it plays the role of STOP.

 Save (e.g. myfunc.m) and run


>> myfunc (2)
ans =
6.1000
Function M-files: example
 stats.m:
function [avg, stdev] = stats( x )
% STATS Mean and standard deviation
% Returns mean (avg) and standard
% deviation (stdev) of the data in the
% vector x, using Matlab functions
avg = mean(x); % function body
stdev = std(x);
end

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);

function a = mean(v, n) % Subfunction


% Calculate average.
a = sum(v)/n;

function m = median(v, n) % Subfunction


% Calculate median.
w = sort(v);
if rem(n, 2) == 1
m = w((n+1) / 2);
else
m = (w(n/2) + w(n/2+1)) / 2;
end
Private functions
 A private function is a function residing in a
subdirectory with the name private. Private
functions are visible only to functions in the parent
directory.
function [ y ] = sqrtDelta( a,b,cfunction
) [ x1, x2 ] = gptb2( a,b,c )
%This function is in a folder %GPTB2 is in parent folder of the private one
% named as private sD = sqrtDelta(a,b,c);
x1 = (-b + sD)/(2*a);
y = sqrt(b^2 - 4*a*c); x2 = (-b - sD)/(2*a);

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)

• Passing a function to another function (often called function functions).


For example, passing a function to integration and optimization
functions, such as integral and fzero.
• Constructing handles to functions defined inline instead of stored in a
program file (anonymous functions).
• Specifying callback functions (for example, a callback that responds to
a UI event or interacts with data acquisition hardware).
• Calling local functions from outside the main function.
Bài tập
 Sử dụng handle của hàm (hoặc đồ thị) để thực hiện:
1. Tích phân: sin(x) + cos(x) trong khoảng: (0 – 3*pi/2);
và (–pi/2 : pi/2)

2. Vẽ đồ thị hàm số:


y = e^x
 Với x = 0 – 10
 Thay đổi màu sắc của đồ thị thành màu “đỏ”
Handle Graphics: Modifying Plots
 You can always get the handle for two different
parts of the plot: the axis, and
x =the figure.
0:pi/20:2*pi;
 gca: get current axis y1 = sin(x);
y2 = exp(x);
 gcf: get current figure
 gco: get current object figure;
h1 = plot(x, y1);

figure;
h2 = plot(x, y2) ;

set(h1, ‘Color’, ‘blue’)


set (h2, ‘Color’, ‘red’)
set(handle,'PropertyName',value)
set(gca, 'XScale','log')
Recursion

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

You might also like