Transcript y = sin(x)

Introduction to
MATrix
LABoratory
Kai-Chun Fan
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
ans =
4.2000
(return)
>> x = (5*2+1.3-0.8)*10/25
x =
4.2000
%
%
%
%
(return)
% 為 comment sign
default variable data type: double
MATLAB stores the result in double ans
in default
基本數學運算
>> (5*2+1.3-0.8)*10/25
ans =
4.2000
(return)
>> x = (5*2+1.3-0.8)* … (return)
10/25 (return)
x =
4.2000
% 式子太長可用 … 換行
Appendix
abs(x)
sqrt(x)
純量的絕對值 or 向量的長度
rat(x)
rats(x)
angle(z) 複數 z 的 phase angle
sign(x)
real(z)
imag(z)
conj(z)
複數 z 的實部
複數 z 的虛部
複數 z 的共軛複數
rem(x,y)
gcd(x,y)
lcm(x,y)
將實數 x 化為分數表示
將實數 x 化為多項分數展開
-1
, if x < 0
0
, if x = 0
1
, if x > 0
x mod y
(int, int)
(int, int)
round(x)
fix(x)
floor(x)
ceil(x)
四捨五入
無條件捨去
└ ┘
┌ ┐
exp(x)
pow2(x)
log(x)
log2(x)
log10(x)
ex
2x
ln
log2x
log10x
sin(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 3
5 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 .* y
ans =
118 118
>> x * y
error
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 3
118 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
% catenate
a =
1 2 3
4 5 6
>> a = [a; 7 8 9];
>> a = [a(1,:) 118; a(2,:) 118; a(3,:) 118]
a =
1 2 3 118
4 5 6 118
7 8 9 118
% inverse
a =
39 39 889
>> a’
a =
39
39
889
% start [: different] : end
>> x = 7 : 13
x =
7 8 9 10 11 12 13
>> y = 7 : 1 : 13
y =
7 8 9 10 11 12 13
>> z = 7 : 4 : 13
z =
7 11
>> a = [1:3; 10:10:30]
a =
1 2 3
10 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.m
for i = 0:2:4,
for j = 1:2,
h(i/2+1, j) = i/(j*4);
end
end
disp(h)
% display, like “cout”
format rat
% use fraction to display
disp(h)
% output
>> kerker (return)
0 0
0.5 1
2 0.5
0 0
1/2 1
2 1/2
While-loop
% while <condition>
% …
% end
x = zeros(1,6); % create an 1 x 6 ZERO matrix
while i <= 6,
x(i) = 1/i;
<
less than
i = i + 1;
end
<=
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 elements
disp('Given random number is greater than 0.5.');
end
>> world118
Given 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
Appendix
min(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
dim = 1 in default;
dim = 1 (column, top to bottom)
dim = 2 (row, left to right)
cumsum(x, [dim])
cumprod(x, [dim])
dot(x, y)
inner product of x and y
cross(x, y)
cross product of x and y
Constants
eps
realmax
realmin
nan
NaN
i
or j
File I/O
• Like C language
• Read from file
filepointer = fopen(‘filename’);
variable = fscanf(filepointer, format, [m n]);
fclose(filepointer);
File I/O Example
fp = fopen('sinx.txt');
A = fscanf(fp, '%g %g', [2 inf]);
fclose(fp);
>> A = A'
A =
0 0.3142
0.6283 0.9425
1.2566 1.5708
1.8850 2.1991
2.5133 2.8274
3.1416 0
0.3090 0.5878
0.8090 0.9511
1.0000 0.9511
0.8090 0.5878
0.3090 0
File I/O
% load filename
x = filename(m, n)
load sinx.txt
A = sinx.txt(:, 1:2);
>> A
A =
0 0.3142
0.6283 0.9425
1.2566 1.5708
1.8850 2.1991
2.5133 2.8274
3.1416 0
0.3090 0.5878
0.8090 0.9511
1.0000 0.9511
0.8090 0.5878
0.3090 0
% A = sinx.txt(inf, 1:2);
Random Number Generators
均勻分佈亂數 rand
常態分佈亂數 randn
常態亂數(Normal (Gaussian))-normrnd
貝他亂數(Beta)-betarnd
二項式亂數(Binomial)- binornd
X's亂數(Chi square)-chi2rnd
極值亂數(Extreme value)-evrnd
指數亂數(Exponential)-exprnd
F亂數(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)-raylrnd
T亂數(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
KER
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, …
2 or More than 2 lines
plot(set1, set2, …)
plot(set1)
hold on;
plot(set2)
…
plot(x1, x2)
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 Plots
axis([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();
#1
#2
#3
#4
#5
#6
#7
#8
subplot(4, 2, 1:2) % #1&#2
subplot(4, 2, [1 3 5]) % #1&#3&#5
Other types of plots
boxplot
箱型圖
plotyy
可用兩種不同 scale 的座標
ezplot
函數圖型
bar
長條圖
errorbar
圖形加上誤差範圍
fplot
較精確的函數圖形
polar
極座標圖
hist
累計圖
rose
極座標累計圖
stairs
階梯圖
stem
針狀圖
fill
實心圖
feather
羽毛圖
compass
羅盤圖
quiver
向量場圖
pie
圓餅圖
boxplot
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')
plotyy
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之應用')
ezplot
ezplot(‘u*sin(u) + v*cos(v) - 2')
bar
x = 1:10;
y = rand(size(x));
bar(x, y)
errorbar
x = linspace(0, 2*pi, 30);
y = sin(x);
e = std(y) * ones(size(x));
errorbar(x, y, e)
fplot
fplot(func, range);
% sampled more precisely
fplot('sin(1/x)', [0.02 0.2])
polar
theta = linspace(0, 2*pi);
% linespace(start, end, [100 in default])
r = cos(4*theta);
polar(theta, r)
hist
hist(x, number of intervals)
x = randn(5000, 1);
hist(x, 20)
rose
X = randn(1000, 1);
rose(x)
stairs
x = linspace(0, 10, 50);
y = sin(x) .* exp(-x/3);
stairs(x, y)
stem
x = linspace(0, 10, 50);
y = sin(x) .* exp(-x/3);
stem(x, y)
fill
x = linspace(0, 10, 50);
y = sin(x) .* exp(-x/3);
fill(x, y, 'b') % ‘b’ means blue.
feather
theta = linspace(0, 2*pi, 20);
z = cos(theta) + i*sin(theta);
feather(z);
compass
theta = linspace(0, 2*pi, 20);
z = cos(theta) + i*sin(theta);
compass(z);
pie
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.設定名稱及南北部爆炸');
References
http://bime-matlab.blogspot.com/
http://www.mathworks.com/help/techdoc/