60
Kai-Chun Fan MATrix LABorator y 2010.12 .30 ntroduction to

Kai-Chun Fan MATrix LABoratory 2010.12.30 Introduction to

Embed Size (px)

Citation preview

Kai-Chun Fan

MATrixLABoratory

2010

.12.30

Introduction to

Agenda

• Basic Usages for Mathematics• Coding environments• Files I/O• Statistic tools• Plot tools

基本操作畫面

>> (prompt) …

How to Use MATLAB

>> DEMO

>> HELP [ SIGNAL ]% same as man [ SIGNAL ] in UNIX

>> google is your good friend.

基本數學運算>> (5*2+1.3-0.8)*10/25 (return)ans =4.2000

>> x = (5*2+1.3-0.8)*10/25 (return)x = 4.2000

% % 為 comment sign% default variable data type: double% MATLAB stores the result in double ans % in default

基本數學運算>> (5*2+1.3-0.8)*10/25 (return)ans =4.2000

>> x = (5*2+1.3-0.8)* … (return)10/25 (return)x = 4.2000

% 式子太長可用 … 換行

Appendixabs(x) 純量的絕對值 or 向量的長度 rat(x) 將實數 x 化為分數表示sqrt(x) rats(x) 將實數 x 化為多項分數展開

angle(z) 複數 z 的 phase angle sign(x)-1 , if x < 0 0 , if x = 0 1 , if x > 0

real(z) 複數 z 的實部 rem(x,y) x mod y

imag(z) 複數 z 的虛部 gcd(x,y) (int, int)

conj(z) 複數 z 的共軛複數 lcm(x,y) (int, int)

round(x) 四捨五入 exp(x) ex

fix(x) 無條件捨去 pow2(x) 2x

floor(x) └ ┘ log(x) ln

ceil(x) ┌ ┐ log2(x) log2x

log10(x) log10xsin(x) sinh(x)

cos(x) cosh(x)

tan(x) tanh(x

asin(x) asinh(x)

acos(x) acosh(x)

atan(x) atanh(x)

atan2(x,y) 四象限的反正切函數

Vector & Matrix

% vector>> x = [1 3 5 2] (return)x = 1 3 5 2

% matrix>> x = [1 3; 5 2] (return)x =1 35 2

X = 3

X 為一個 1 x 1 matrix[3]

Vector & Matrix

>> x = [1 3 5 2]; (return)>> y = 2 * x + 1 (return)y =3 7 11 5

% y is an array for 2 * x(i) + 1

;抑制輸出

>> x = [1 3 5 2]; (return)>> y = 2 * x + 1 (return)y =3 7 11 5

>> x = [1 3 5 2] (return)x = 1 3 5 2>> y = 2 * x + 1 (return)y =3 7 11 5

Operators for Vector and Matrix

M = A B◎ -- ◎處可為加法 (+)、減法 (-)、乘法 (*)、左除 (\)、右除 (/)

M = A. B◎ -- ◎處可為乘法 (*)、乘幂 (^)、左除 (\)、右除 (/)

M = A c◎ -- ◎處可為加法 (+)、減法 (-)、乘法 (*)、乘幂 (^)、右除 (/)

M = c B◎ -- ◎處可為加法 (+)、減法 (-)、乘法 (*)、乘幂 (^)、左除 (\)、右除 (./)

Special Operators

• M = A . B◎

>> x = [1 2];>> y = [118 59];>> x .* yans = 118 118

>> x * yerror

Index for Vector & Matrix% variable(index)>> x = [1 3 5 2]; (return)>> x(1) = 118 (return)x =118 3 5 2

>> x = [1 3; 5 2]; (return)>> x(2, 1) = 118 (return)x =1 3118 2

% index starts from 1, not 0.

Index for Vector & Matrix

% range index>> x = [1 2 3; 4 5 6; 7 8 9]; (return)>> x(2, 1:3) (return)ans = 4 5 6

>> x(1:3, 2) (return)ans =2 5 8

Add & Delete

% add element>> x = [1 3 5 2]; (return)>> x(6) = 631 (return)x = 1 3 5 2 0 631

% delete element>> x(3) = []; (return)>> x (return)x=1 3 2 0 631

Catenate & Inverse% catenatea =1 2 34 5 6>> a = [a; 7 8 9];>> a = [a(1,:) 118; a(2,:) 118; a(3,:) 118]a =1 2 3 1184 5 6 1187 8 9 118

% inversea =39 39 889>> a’a =3939889

:% start [: different] : end>> x = 7 : 13x =7 8 9 10 11 12 13

>> y = 7 : 1 : 13y =7 8 9 10 11 12 13

>> z = 7 : 4 : 13z =7 11

>> a = [1:3; 10:10:30]a =1 2 310 20 30

Variables in Workspace% information>> whos (return)name size bytes class

a 2x4 64 double array b 4x2 64 double array ans 1x1 8 double array x 1x1 8 double array y 1x1 8 double array z 1x1 8 double array

grand total is 20 elements using 160 bytes

% release>> clear a>> a??? Undefined function or variable ‘a'.

Code in Files

% write your code in files, *.m% for example, kerker.m

>> kerker (return)

For-loop% for <variable> = <vector>% …% end

% in kerker.mfor i = 0:2:4,for j = 1:2,

h(i/2+1, j) = i/(j*4);endenddisp(h) % display, like “cout”format rat % use fraction to displaydisp(h)

% output>> kerker (return)0 00.5 12 0.50 01/2 12 1/2

While-loop% while <condition>% …% end

x = zeros(1,6); % create an 1 x 6 ZERO matrixwhile i <= 6,

x(i) = 1/i;i = i + 1;

end

< less than

<= less than or equal to

> larger than

>= larger than or equal to

== equal to

~= NOT equal to ( != in C )

& AND ( && in C )

| OR ( || in C )

~ NOT ( ! in C )

if% if <condition>% …% end

% in world118.m

if rand(1,1) > 0.5, % create an 1x1 matrix with random elementsdisp('Given random number is greater than 0.5.');

end

>> world118Given random number is greater than 0.5.

eye(x, y) Create an Identity matrix

ones(x, y, …) Create an ONEs matrix

zeros(x, y, …)

Create a ZEROs matrix

rand(x, y, …) Create a RANDOM NUMBER matrix

break

Appendixmin(x) minimum in x

max(x) maximum in x

mean(x) mean of x

median(x) median of x

std(x) stander deviation of x

diff(x) x(i+1)-x(i), for all i

sort(x, [dim], [mode]) mode = ‘ascend(default)’ or ‘decend’dim = 1 (every column, default), 2 (every row)

sortrows(x, column j) sort rows along column j.‘–j’ means ‘decend’

length(x) number of elements in x

norm(x) euclidean length of x

sum(x) sum of x

prod(x) product of x

cumsum(x, [dim]) dim = 1 in default;dim = 1 (column, top to bottom)dim = 2 (row, left to right)cumprod(x, [dim])

dot(x, y) inner product of x and y

cross(x, y) cross product of x and y

pirealmaxrealmin

nargin

nargout

i n f

eps

nanNaN

i or j

C o n s t a n t s

File I/O

• Like C language

• Read from filefilepointer = fopen(‘filename’);variable = fscanf(filepointer, format, [m n]);fclose(filepointer);

fp = fopen('sinx.txt');A = fscanf(fp, '%g %g', [2 inf]);fclose(fp);

>> A = A'A =0 0.31420.6283 0.94251.2566 1.57081.8850 2.19912.5133 2.82743.1416 00.3090 0.58780.8090 0.95111.0000 0.95110.8090 0.58780.3090 0

File I/O Example

File I/O% load filename

x = filename(m, n)load sinx.txtA = sinx.txt(:, 1:2); % A = sinx.txt(inf, 1:2);

>> AA =0 0.31420.6283 0.94251.2566 1.57081.8850 2.19912.5133 2.82743.1416 00.3090 0.58780.8090 0.95111.0000 0.95110.8090 0.58780.3090 0

Random Number Generators均勻分佈亂數 rand常態分佈亂數 randn常態亂數 (Normal (Gaussian))-normrnd貝他亂數 (Beta)-betarnd二項式亂數 (Binomial)- binorndX's 亂數 (Chi square)-chi2rnd極值亂數 (Extreme value)-evrnd指數亂數 (Exponential)-exprndF 亂數 (F)-frnd伽瑪亂數 (Gamma)-gamrnd伽瑪亂數 (Gamma (unit scale))-randg幾何亂數 (Geometric)-geornd超幾何亂數 (Hypergeometric)-hygernd反威夏亂數 (Inverse Wishart)-iwishrnd常態對數亂數 (Lognormal)-lognrnd多變異亂數 (Multivariate normal)-mvnrnd多變 T 亂數 (Multivariate t)-mvtrnd負二項式亂數 (Negative binomial)-nbinrnd 非中央 F 亂數 (Noncentral F)-ncfrnd 非中央亂數 (Noncentral)-nctrnd非中央 X's 亂數 (Noncentral Chi-square)-ncx2rnd波義松亂數 (Poisson)-poissrnd定群樣本亂數 (finite population)-randsample魏利亂數 (Rayleigh)-raylrndT 亂數 (T)- trnd離散均勻亂數 (Discrete uniform)-unidrnd均勻亂數 (Uniform)-unifrnd魏伯亂數 (Weibull)-wblrnd威夏亂數矩陣 (Wishart)-wishrnd

% *nd are not “dname.”

Random Number Generators

random(‘dname', mean, var, m, n)

畫 圖圖 畫

xy - Plane

Basic– plot(…)

• x-axis: linear scale• y-axis: linear scale

– loglog(…)• x-axis: log scale• y-axis: log scale

– semilogx(…)• x-axis: log scale• y-axis: linear scale

– semilogy(…)• x-axis: linear scale• y-axis: log scale

plot(x1)- y-axis adopts the column number

plot(x1, y1)

plot(x1, y1, LineSpec, ‘PropertyName’, Property value, ‘PropertyName’, Property value, …)

- LineWidth, MarkerEdgeColor, MarerFaceColor, MarkerSize, …

KER

plot(set1, set2, …)

plot(set1)hold on;plot(set2)…

plot(x1, x2)

2 or More than 2 lines

x = -pi:0.1:pi;y = sin(x);plot(x,y)

x = -pi:pi/10:pi;y = tan(sin(x)) - sin(tan(x));plot(x,y,'--rs',...

'LineWidth',2,...'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10)

LineSpec

char color char Line type Char Marker

y 黃色 - 實線 . 點k 黑色 : 點線 o 圓w 白色 -. 點虛線 x x

b 藍色 -- 虛線 + +

g 綠色 none 無 * *

r 紅色 s Square

c 亮青色 d Diamond

m 錳紫色 none 無

其它線參數

點我http://www.mathworks.com/help/techdoc/ref/plot.html

Other Properties for Plotsaxis([xmin, xman, ymin, ymax])

- range of x-axis and y-axis.- the dot out of the range will not be presented.

xlabel(‘name for x-axis’)

ylabel(‘name for y-axis’)

title(‘title for the plot’)

test(x, y, text, alignment base, position)- notes for a specific point

legend(‘note for line1’, ‘note for line2’, …)

grid on;- show the grid line

x = -pi:.1:pi;y = sin(x);p = plot(x,y)xlabel('-\pi \leq \Theta \leq \pi')ylabel('sin(\Theta)')title('Plot of sin(\Theta)') text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',...

'HorizontalAlignment','left') set(p,'Color','red','LineWidth',2)set(gca,'XTick',-pi:pi/2:pi)set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})

subplot

subplot(i, j, #) plot();

subplot(4, 2, 1:2) % #1&#2subplot(4, 2, [1 3 5]) % #1&#3&#5

#1 #2

#3 #4

#5 #6

#7 #8

Other types of plotsboxplot 箱型圖plotyy 可用兩種不同 scale 的座標ezplot 函數圖型bar 長條圖errorbar 圖形加上誤差範圍 fplot 較精確的函數圖形 polar 極座標圖hist 累計圖rose 極座標累計圖stairs 階梯圖stem 針狀圖fill 實心圖feather 羽毛圖compass 羅盤圖quiver 向量場圖pie 圓餅圖

x1 = normrnd(5, 1, 100, 1);x2 = normrnd(6, 1, 100, 1);boxplot([x1, x2], 'notch', 'on')

boxplot

x = randn(100,25);subplot(2,1,1) boxplot(x)subplot(2,1,2) boxplot(x,'plotstyle','compact')

boxplot

x = 0:0.01:10;y1 = 100 * exp(-0.1*x) .* sin(x);y2 = 0.8 * exp(-0.5*x) .* sin(10*x);[ax, h1, h2] = plotyy(x, y1, x, y2, ‘plot’);set(get(ax(1),‘Ylabel’), ‘String’, ‘ 左側 y1 函數’ )set(get(ax(2),‘Ylabel’), ‘String’, ‘ 右側 y2 函數’ )set(h1,‘Linewidth’,4)set(h2,‘LineStyle’, ‘:’, ‘color’, 'k')xlabel(' 時間 0-10 \mus')title(' 指令 plotyy 之應用 ')

plotyy

ezplot(‘u*sin(u) + v*cos(v) - 2')

ezplot

x = 1:10; y = rand(size(x)); bar(x, y)

bar

x = linspace(0, 2*pi, 30); y = sin(x); e = std(y) * ones(size(x)); errorbar(x, y, e)

errorbar

fplot(func, range);% sampled more precisely

fplot('sin(1/x)', [0.02 0.2])

fplot

theta = linspace(0, 2*pi);% linespace(start, end, [100 in default]) r = cos(4*theta); polar(theta, r)

polar

hist(x, number of intervals)

x = randn(5000, 1);hist(x, 20)

hist

X = randn(1000, 1); rose(x)

rose

x = linspace(0, 10, 50); y = sin(x) .* exp(-x/3); stairs(x, y)

stairs

x = linspace(0, 10, 50); y = sin(x) .* exp(-x/3); stem(x, y)

stem

x = linspace(0, 10, 50); y = sin(x) .* exp(-x/3); fill(x, y, 'b') % ‘b’ means blue.

fill

theta = linspace(0, 2*pi, 20); z = cos(theta) + i*sin(theta); feather(z);

feather

theta = linspace(0, 2*pi, 20); z = cos(theta) + i*sin(theta); compass(z);

compass

Y = [10 13 40 50]; subplot(2,2,1), pie(Y)title('1. 未加任何標示 ');subplot(2,2,2), pie(Y,[0 0 0 1]) title('2. 第四部產生爆炸 ');subplot(2,2,3), pie(Y,{' 東部 ',' 西部 ',' 南部 ',' 北部 '}) title('3. 設定各組名稱 '); subplot(2,2,4), pie(Y,[0 0 1 1],{' 東部 ',' 西部 ',' 南部 ',' 北部 '}) title('4. 設定名稱及南北部爆炸 ');

pie