Post on 30-Dec-2015
description
數值方法 2008, Applied Mathematics NDHU 1
• Matrix Manipulation• Plotting
MATLAB Programming
數值方法 2008, Applied Mathematics NDHU 2
Matrix creation
Matrix generation eye ones zeros diag rand repmat reshape
Vector generation linspace equi-spacing
數值方法 2008, Applied Mathematics NDHU 3
Exercise
matrix creation
數值方法 2008, Applied Mathematics NDHU 4
rand
rand(m,n)Create a matrix composed of m rows and n
columns. All of its elements are uniformly sampled from [0 1]
數值方法 2008, Applied Mathematics NDHU 5
Matrix size
A=rand(m,n)size(A)
Return row and column numbers of matrix A
數值方法 2008, Applied Mathematics NDHU 6
eye(n), ones(n), zeros(n)
eye(n)Create an nxn identical matrix
ones(n)Create an nxn matrix with all elements
identical to onezeros(n)
Create an nxn zero matrix
數值方法 2008, Applied Mathematics NDHU 7
Diagonal matrix
v=[1 2 3 4 5]diag(v)
Create an diagonal matrix whose diagonal vector is identical to v
數值方法 2008, Applied Mathematics NDHU 8
Matrix multiplication
Validity A*B is valid if the column number of A is
identical to the row number of Bones(5,1)*[1 2 3 4 5]
Form a 5x5 matrix. Each of its five rows equals [1 2 3 4 5]
數值方法 2008, Applied Mathematics NDHU 9
Matrix replication
v=[1 2 3 4 5]repmat(v,n,m)
Repeat v n times vertically Repeat the result m times horizontally
repmat(v,5,1)
數值方法 2008, Applied Mathematics NDHU 10
Reshape
A=rand(m,n)
B=reshape(A,p,q)Validity: mxn needs identical to pxqB is a pxq matrixColumn major reshaping of a matrix
數值方法 2008, Applied Mathematics NDHU 11
Column major
A=[1 2 3;4 5 6];
B=reshape(A,3,2)
1 5
4 3
2 6
數值方法 2008, Applied Mathematics NDHU 12
Column major
6
3
5
2
4
1A
6
3
5
2
4
1
B
B=reshape(A,3,2)
數值方法 2008, Applied Mathematics NDHU 13
Column major
A=[1 2 3;4 5 6;7 8 9;10 11 12]B=reshape(A,3,4)
數值方法 2008, Applied Mathematics NDHU 14
Vector creation
Direct inputa=[1 2 3 4 5 6 7 8 9 10]
Spacinga=1:10a=1:1:10a=1:2:100A=100:-5:1
數值方法 2008, Applied Mathematics NDHU 15
Linspace
v=linspace(a,b,n)v is a vector which consists of n elementsThese elements equally partition the interval
[a b]
數值方法 2008, Applied Mathematics NDHU 16
Plot
Plot pointsplot(x,y,’.’)x and y have same length, such as nThis instruction draws n points, denoted by
{(xi yi)}i
xi denotes the ith element of vector x
yi denotes the ith element of vector x
數值方法 2008, Applied Mathematics NDHU 17
Plot points and lines
plot(x,y)n points and lines connecting two
consecutive points
數值方法 2008, Applied Mathematics NDHU 18
Plot a function
x=linspace(-5,5,100);
y=cos(x);
plot(x,y)The output contains a set of points
specified by vectors x and yTwo consecutive points are connected
數值方法 2008, Applied Mathematics NDHU 19
subplot
x=linspace(-5,5,100);
subplot(2,1,1)
plot(x,cos(x))
subplot(2,1,2)
plot(x,sin(x))