信号實驗(01)MATLAB 程式設計基礎及典型執行個體
一.例子
1.1.duiqi.m
function [f1_new, f2_new, n ] = duiqi(f1,n1,f2,n2)
% 功能:将兩個序列對齊,以實作兩個序列之間的運算
% 輸入:
% (1 ) f1,f2: 原來的兩個序列;
% (2 ) n1,n2: f1,f2 所對應的時間變量範圍;
% 輸出:
% f1_new, f2_new :對齊後的兩個序列
% n : 對齊後的兩個序列的時間變量範圍
%-------------------------------------------------------------------------
a = min(min(n1), min(n2));
b = max(max(n1), max(n2));
n = a : b;
f1_new = zeros(1, length(n));
f2_new = zeros(1, length(n));
tem1 = find((n>=min(n1))&(n<=max(n1))==1);
f1_new(tem1) = f1;
tem2 = find((n>=min(n2))&(n<=max(n2))==1);
f2_new(tem2) = f2;
二.實驗
2.1.建立自己姓名檔案夾
2.2.繪制曲線
繪制信号 x ( t ) = e − 2 t s i n ( 2 3 t ) x(t)=e^{-\sqrt{2}t}sin(\frac{2}{3}t) x(t)=e−2
tsin(32t)的曲線,t 的範圍在 0 30 s 0 ~ 30s 0 30s,取樣時間間隔為 0.1 s 0.1s 0.1s.
% 繪制信号 的曲線,t 的範圍在 0 ~ 30s,取樣時間間隔為 0.1s.
t = 0:0.1:30;
x = exp(-sqrt(2) .* t) .* sin(2 / 3 .* t);
plot(t,x);
2.3.離散分段函數
在 n = [ − 10 : 10 ] n = [-10:10] n=[−10:10] 範圍産生離散序列:
x ( n ) = 2 n , − 3 ≤ n ≤ 3 = 0 , o t h e r x(n)=2n,-3\le n\le 3\\ =0,other x(n)=2n,−3≤n≤3=0,other
并繪圖。
n = (-10:1:10);
% 生成一樣次元x
x = zeros(size(n));
for i = 1:length(n)
if -3 <= n(i) && n(i) < 3
x(i) = 2 * n(i);
else
x(i) = 0;
end
end
% 是離散序列
plot(n, x, '.');
2.4.根據圖像
% 是一個小括号
t = (-3:0.001:3);
% 生成一樣次元x
y = zeros(size(t));
for i = 1:length(t)
if -1 <= t(i) && t(i) < 1
y(i) = 2 ;
% elseif 是不分開的
elseif 1 <= t(i) && t(i) < 2
y(i) = 1;
else
y(i) = 0;
end
end
% 是離散序列
% staris(t, y);
plot(t, y);
xlabel('X軸');ylabel('Y軸');
% 先畫圖再控制
axis([-2, 3, 0, 3]);
2.5.對齊函數
利用 duiqi.m 函數,求 add_f(k) = f 1 (k)-f 2 (k),pro_f(k) = f 1 (k)×f 2 (k),并以子圖形式畫出 f 1 (k)、f 2 (k)、add_f(k)、pro_f(k)。
clear;
f1 = 0:5;
f2 = 6:-1:0;
n1 = -1:4;
n2 = -5:1;
% function [f1_new, f2_new, n ] = duiqi(f1,n1,f2,n2)
[f1_new, f2_new, n] = duiqi(f1, n1, f2, n2);
add_f = f1_new - f2_new;
pro_f = f1_new .* f2_new;
subplot(2, 2, 1);
% 原來得不變
stem(n1, f1);
xlabel('n1');
ylabel('f1');
grid on;
subplot(2, 2, 2);
stem(n2, f2);
xlabel('n2');
ylabel('f2');
grid on;
subplot(2, 2, 3);
stem(n, add_f);
xlabel('n3');
ylabel('add_f');
grid on;
subplot(2, 2, 4);
stem(n, pro_f);
xlabel('n');
ylabel('pro_f');
grid on;
三.思考題
整理并給出“實驗内容與步驟”(2)、(3)、(4)、(5)中的程式代碼與産生
的圖形;并回答下面的問題。
3.1.
在調用某一函數檔案時,該檔案中除了輸入、輸出變量外的其它變量在調用 函數結束後是否還存在?這些變量是全局還是局部變量?
不存在,局部變量
3.2.
設 n = -10:0.2:20,你可以通過哪些方法檢視向量 n 的維數?經過關系運 算 y = (n >= 3)以後,y 的維數是多少?y又等于什麼?
n = -10:0.2:20;
% 151 = (20-(-10)) / 0.2 + 1
length(n)
y = (n >= 3)
% 得到n就是真假
% y = [0,0,...]
length(y)
有
length()
方法檢視n的維數,y的維數是151,y = [0,0,0,…1,1,1]
3.3.
通過 MATLAB 的幫助系統,學習 fliplr 函數的功能和使用方法。再此基礎上,寫出能夠産生如下圖形的程式,
x ( n ) = 2 n , − 4 ≤ n ≤ 4 x(n)=2^n,-4\le n \le 4 x(n)=2n,−4≤n≤4
n = -4:4;
x_n = 2.^n;
subplot(1, 2, 1);
stem(n, x_n);
xlabel('n');
ylabel('x(n)')
% 左右翻轉
subplot(1, 2, 2);
stem(n, fliplr(x_n));
xlabel('n');
ylabel('x(-n)')