1012 matlab 教學

28
1012 MATLAB 教教 教教教 2014/02/25

Upload: odysseus-grimes

Post on 03-Jan-2016

85 views

Category:

Documents


0 download

DESCRIPTION

1012 MATLAB 教學. 羅英倉 2014/02/25. What is MATLAB?. MAT rix LAB oratory 的 縮寫 1984 年由 MathWorks 公司 推出 主要特色 強大的數值運算 ( numeric computation) 能力 完整的矩陣運算指令 許多 不同領域 的工具箱 (Toolbox ) 、函式庫 影像處理 、訊號 處理、金融分析、生物資訊 應用 algorithm development, data visualization, data analysis, and numeric computation. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 1012 MATLAB  教學

1012 MATLAB 教學

羅英倉 2014/02/25

Page 2: 1012 MATLAB  教學

What is MATLAB? MATrix LABoratory 的縮寫 1984 年由 MathWorks 公司推出 主要特色

強大的數值運算 (numeric computation) 能力 完整的矩陣運算指令 許多不同領域的工具箱 (Toolbox) 、函式庫

影像處理、訊號處理、金融分析、生物資訊 應用

algorithm development, data visualization, data analysis, and numeric computation

2

Page 3: 1012 MATLAB  教學

Development Environment 4 個主要視窗

Workspace( 變數區域 ) 、 Command History( 命令歷史列 ) 、 Command History 、 Current Folder

3

Page 4: 1012 MATLAB  教學

Operators 算術運算子

沒有 ++ 、 -- + 、 - 、 * 、 /( 除以 ) 、 \( 除 ) 、 ^( 次方 ) >> 100/5

ans = 20 比較運算子

>= 、 <= 、 > 、 < 、 == 、 ~= 邏輯運算子

& 、 | 、 ~ Element-by-Element 運算“ .”

A = [1 1 1;1 2 3;1 3 6];

4

A.^2 = 1 1 1 1 4 9 1 9 36

A^2 = 3 6 10 6 14 25 10 25 46

A = 1 1 1 1 2 3 1 3 6

Page 5: 1012 MATLAB  教學

Operators 運算式最後加分號 (;) ,就不會顯示運算結果

>> 100/5; % 不會輸出運算結果 多個運算式之間,可用逗號 (,) 或分號 (;) 隔開

x=1,y=2,z=3 x=1;y=2;z=3

% 註解符號,類似 C 語言的 // 快捷鍵: Ctrl+R( 註解 ) 、 Ctrl+T( 解除註解 )

5

Page 6: 1012 MATLAB  教學

Variables (1/3) 區分大小寫 (case sensitive) 變數第一個字母必需是英文字母

Ex: num_students = 30 不需要預先宣告變數 輸入變數名稱,會顯示變數值 預設變數

ans: Most recent answer pi: 3.1416 i or j: 虛數基本單位,也就是根號負 1 Inf: 無窮大 (Infinity) NaN: 不存在 realmin: 可以使用的最小實數 realmax: 可以使用的最大實數6

Page 7: 1012 MATLAB  教學

Matrices and Arrays 矩陣 index 從 1 開始算 產生一個 1x3 的矩陣,可用空格或逗號隔開

x=[10 2 3] 或 y=[1,2,3] 產生一個 2x3 的矩陣,分號作為換列的分隔符號

m=[11 12 13; 21 22 23] 直接存取該位置的值

x(2)=2 m(2,3)=23

亦可由變數組成 z=[x y] % z=[10 2 3 1 2 3]

刪除元素 z(2)=[] % z=[10 3 1 2 3]

增加元素 z(6)=100% z=[10 3 1 2 3 100]7

Page 8: 1012 MATLAB  教學

Matrices and Arrays 矩陣列跟欄的操作

x=[1 2 3; 4 5 6] x(2,:) % 顯示第二列資料,其結果 4 5 6 x(:,3) % 顯示第三欄資料,其結果 3 6 x(2,1:2)=7 % x=[1 2 3; 7 7 6] x(1,end) % ans = 3

從哪裡到哪裡 a=1:3 % 從 1~3 每次間隔 1 b=1:.5:3 % 從 1~3 每次間隔 0.5 c=linspace(0,10,20) % 從 0~10 分成 20 等分 %linspace(Generate linearly spaced vectors) x(2:6)=1 % 將 x 向量的第二到六個設定 1

8

Page 9: 1012 MATLAB  教學

矩陣基本運算 x = [2 2 2];

y = [3 3 3];z = [1 1 1];x+y-z = [4 4 4]

矩陣相乘A = [5 3 2 6];A = 5 3 2 6B = [-4 9 0 1]’B = -4 9 0 1A*B = 13

如果要 element by element 的相乘,應該用” .*” ,而不是” *”

9

Page 10: 1012 MATLAB  教學

矩陣常用函式 zeros: 配置零矩陣

zeros(3) % 產生一個 3-by-3 的零矩陣 ones: 配置每個 element 都是 1 的矩陣 eye: 配置單位矩陣

eye(3) rand, randi, randn: 配置值為亂數的矩陣 size: 取得矩陣的大小 length: 取得陣列的長度 inv: 取得反矩陣 sort: 排序 magic(n): 產生 n x n 的魔方陣 ( 每行、每列、和對角線的總和都

一樣 )

10

Page 11: 1012 MATLAB  教學

數學常用函式 min 、 median 、 max mean: 平均 sum: 總和 abs: 取絕對值 ceil 、 floor 、 round( 四捨五入 ) sin 、 cos 、 tan 、 asin 、 acos 、 atan exp: 自然指數 log(x): 自然對數 ln(x), log2, log10 sqrt( 開根號 ) rem(x,y): x 除以 y 的餘數 sign: 回傳 -1( 負數 ), 0( 零 ) or 1( 正數 ) imag( 取虛數部份 ) 、 real( 取實數部份 )

11

Page 12: 1012 MATLAB  教學

一般常用函式 clear: 清除所有變數宣告

亦可僅清除單一變數 clear x; clc: 清除 Command Window 畫面 disp: 顯示文字或陣列

12

Page 13: 1012 MATLAB  教學

訊號系統常用函式 conv(a,b):Convolution fft2(x):Fast Fourier transform

13

Page 14: 1012 MATLAB  教學

Custom M-file 副檔名 : *.m File->New->M-File or File->New->Script 檔名必須與函數名稱相同 M-file 函式裡面定義的任何變數皆是 local variable 一般習慣將指令先寫個 M-File ,然後執行該 M-File( 等同於在

Command Window 下指令 ) ,以便多次執行相同指令 Function 格式

function [ output_args ] = FuncName( input_args )% UNTITLED Summary of this function goes here% Detailed explanation goes herecodereturn

14

Page 15: 1012 MATLAB  教學

M-file Examplefunction [z] = add(x,y)z=x+y;return

在 Command Window 可以直接呼叫 add() add(4,80) Current Folder 要設定在 M-file 所在位置,不然會找不到該函式,

發生” ??? Undefined function or method” 的錯誤

15

Page 16: 1012 MATLAB  教學

if/elseif/else 與 C 語言相同,看情況使用 elseif 跟 else if expression1

commandselseif expression2

commandselseif …

……

elsecommands

end

16

Page 17: 1012 MATLAB  教學

For Loop for i=1:10 % i 從 1~10 間隔 1

x(i)=sin(i)end

for i=1:2:10 % i 從 1~10 間隔 2x(i)=cos(i)

end for i=10:-1:1 % i 從 10~1 每次少 1

x(i)=tan(i)end

for 迴圈方法較慢,可直接向量操作 i=1:10;

x=sin(i)

17

Page 18: 1012 MATLAB  教學

while loop while

i=0;while i<10

i = i+1end

迴圈可使用 break , continue

18

Page 19: 1012 MATLAB  教學

Graphics (1/4) plot: 畫 2D 線圖 樣式設定

顏色 y(yellow) 、 m(magenta) 、 c(cyan) 、 r(red) 、 green(g) 、 b(blue)

、 white(w) 、 black(b) 線條樣式

.(point) 、 o(circle) 、 x(x-mark) 、 +(plus) 、 *(star) 、 -(solid line) 、 :(dotted line) 、 --(dashed)

19

x=linspace(1,2*pi,30);y=sin(x);plot(x,y);

z=cos(x);plot(x,y,x,z);

plot(x,y,'o',x,z,'g*');

Page 20: 1012 MATLAB  教學

Graphics (2/4) stem(x,y): 繪製離散圖形 grid: 格線 xlabel('x name'): x 軸名稱 ylabel('y name'): y 軸名稱 title('stem(x,sin(x))'): 圖片抬頭 text(0,0, 'text'): 特定位置加上文字 axis([xmin xmax ymin ymax]): x 、 y 軸的範圍

20

1 2 3 4 5 6 7-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x name

y na

me

stem(x,sin(x))

x=linspace(1,2*pi,30);y=sin(x);stem(x,sin(x));grid on;xlabel('x name');ylabel('y name');title('Test Title');

Page 21: 1012 MATLAB  教學

Graphics (3/4) subplot(共幾列 ,共幾欄 , 第幾個位置 )%選擇輸出的位置

分好幾個小圖顯示 Example

21

x=linspace(0,2*pi,30);y=sin(x);z=cos(x);a=2*sin(x).*cos(x);b=tan(x);subplot(2,2,1);plot(x,y);subplot(2,2,2);plot(x,z);subplot(2,2,3);plot(x,a);subplot(2,2,4);plot(x,b);

Page 22: 1012 MATLAB  教學

Graphics (4/4) hold on / hold off

在已有的圖案上,加上新的圖案 % plot(x,z) 的結果會覆蓋 plot(x,y) 的結果

% 在 plot(x,z) 之前加上 hold on ,保留之前畫得結果

22

x=linspace(1,2*pi,30);y=sin(x);plot(x,y);z=cos(x);plot(x,z);

x=linspace(1,2*pi,30);y=sin(x);plot(x,y);z=cos(x);hold onplot(x,z);hold off

Page 23: 1012 MATLAB  教學

Input/Output fprintf

print to the screenx= 100;fprintf('hello world! %d\n',x);

寫檔x = 0:.1:1;y = [x; exp(x)];% open the file with write permissionfid = fopen('c:\exp.txt', 'w');fprintf(fid, '%6.2f %12.8f\n', y);fclose(fid);% view the contents of the filetype exp.txt

input: select=input('selection(number):');23

Page 24: 1012 MATLAB  教學

音效 (1/3) 讀取音效

[y,fs]=wavread('file.wav'); 可設定讀取範圍,如 wavread('file.wav',[3000,5000]);

播放音效 sound(y,fs); wavplay(y*m,fs*n);

y 增加倍數 (m) 可增大音量, fs 增加倍數 (n) 會影響音訊速度 錄製音效

y=wavrecord(n, fs); %讀入 n 點資料 輸出檔案

wavwrite(y, fs, nbits, waveFile)

24

Page 25: 1012 MATLAB  教學

音效 (2/3) wavread 範例

wavrecord 範例

25

fs=12000; % 取樣頻率 12000 Hz

fprintf('按任意鍵後開始 2秒錄音: '); pause

fprintf('錄音中 ...');

y=wavrecord(2*fs, fs); %duration*fs 是錄音資料點數fprintf('錄音結束 \n');

fprintf('按任意鍵後開始播放: '); pause

wavplay(y,fs);

[y, fs]=wavread('run.wav');

sound(y, fs); % 播放此音訊time=(1:length(y))/fs; % 時間軸的向量plot(time, y); % 畫出時間軸上的波形

Page 26: 1012 MATLAB  教學

音效 (3/3) 音效 Convolution範例

26

file='sentence.wav';

[y,fs,nbits]=wavread(file);

file2='Hallway_IR.wav';

[y2,fs2,nbits2]=wavread(file2);

test=conv(y,y2); % 迴旋積運算wavwrite(test,fs2,'test.wav');

time=(1:length(test))/fs; %時間軸plot(time,test);

Page 27: 1012 MATLAB  教學

影像處理範例 imread(‘filename.jpg'): 讀取影像檔案 Example:

filename = 'dog.jpg';rgb_image = imread(filename);figure,imshow(rgb_image);%彩色轉成灰階gray_image = rgb2gray(rgb_image); figure,imshow(gray_image);imwrite(gray_image, 'gray_dog.jpg'); %write new image% 影像模糊化h = fspecial('gaussian',10,10);blur_rgb_image =imfilter(rgb_image,h);figure,imshow(blur_rgb_image);

27

Page 28: 1012 MATLAB  教學

影像處理範例 灰階影像的邊界

edge_img = edge(gray_image,'canny');imshow(edge_img);

28