Contents
一般形式: 變量 = 表達式(數)
a = [1 2 3 ; 4 5 6 ; 7 8 9 ] %矩陣形式賦值. a = 1:2:10 %固定步長的矩陣. zeros(3,2) %三行兩列的全零矩陣. who % 檢查工作空間的變量 whos % 檢查存於工作空間變量的詳細資料
a = 1 2 3 4 5 6 7 8 9 a = 1 3 5 7 9 ans = 0 0 0 0 0 0 Your variables are: A B C X Y Z a ans b f1 f2 fs i num t x y y1 y2 yy Name Size Bytes Class Attributes A 3x3 72 double B 3x3 72 double C 3x3 72 double X 21x21 3528 double Y 21x21 3528 double Z 21x21 3528 double a 1x5 40 double ans 3x2 48 double b 1x32 256 double f1 1x1 8 double f2 1x1 8 double fs 1x1 8 double i 1x1 8 double num 1x1 8 double t 1x221 1768 double x 1x21 168 double y 1x21 168 double y1 1x126 1008 double y2 1x126 1008 double yy 1x221 1768 double
常用函數:
%* norm 范數 % * det 行列式 % * inv 方陣的逆矩陣 % * size 矩陣的階數 % * rank 秩 % * trace 跡 % * eig 特征值和特征向量 % * ^ 乘方運算 % * sqrtm 開方運算 % * expm 指數運算 % * logm 對數運算 A = [6 7 5 ; 3 6 9 ; 4 1 5 ] B = 20 + A C = inv (A) * B eig(C) %求矩陣的特征根 % 矩陣的乘方運算和開方運算 A = [6 7 5 ; 3 6 9 ; 4 1 5 ] B = A^2 C = sqrtm(B)
A = 6 7 5 3 6 9 4 1 5 B = 26 27 25 23 26 29 24 21 25 C = 3.8571 2.8571 2.8571 -0.9524 0.0476 -0.9524 1.9048 1.9048 2.9048 ans = 4.8095 1.0000 1.0000 A = 6 7 5 3 6 9 4 1 5 B = 77 89 118 72 66 114 47 39 54 C = 6.0000 7.0000 5.0000 3.0000 6.0000 9.0000 4.0000 1.0000 5.0000
- if語句
- 循環語句
x = 32 ; y = 86; if x > y 'x 大於 y' elseif x < y 'x 小於 y' elseif x == y ' x 等於y' else 'error' end
ans = x 小於 y
-
for 循環的基本格式為:
for 循環變量 = 起始值 : 步長 : 終止值
循環體
end
% for循環使用示例 a = 0; for i = 1:1:10 a = a + i ; end a
a = 55
-
while循環語句基本格式為
while 表達式
循環體
end
% while循環使用示例 num = 0; a = 5; while a >1 a = a/2; num = num + 1; end num
num = 3
1.2.4 基本繪圖方法
- plot 二維線性圖
- subplot 繪制子圖
- figure() 創建一個圖的窗口
- titel 圖的標題
- xlabel x坐標
- ylabel y坐標
- grid 圖顯示網格
- hold 保持當前圖形
- clf 清除圖形和屬性
- mesh 三維網線圖
- plot3 三維圖形
- surf 三維表面圖
- 繪圖的基本步驟
- 三維圖形的繪制
- 空間曲面的繪制
繪圖的基本步驟:
x = -pi:.1:pi; y1 = sin(x); y2 = cos(x); %准備繪圖數據 figure(1) %打開圖形窗口 subplot(2,1,1) %確定第一幅圖繪圖窗口 plot(x,y1) %以x,y1繪圖 title('繪圖的基本步驟') %為第一幅圖設置標題:"繪圖的基本步驟" grid on %顯示網格線 subplot(2,1,2) %確定第二幅圖繪圖窗口 plot(x,y2) %以x,y2繪圖 xlabel('time') %為第二幅設置x坐標名'time' ylabel('y') %為第二幅設置y坐標名'y' figure(2) %打開圖形窗口 subplot(1,2,1),stem(x,y1,'r') %繪制紅色的脈沖圖 subplot(1,2,2),errorbar(x,y1,'g') %繪制綠色的誤差條形圖
三維圖形的繪制
figure(3) x = 0:0.1:4*pi; y1 = sin(x); y2 = cos(x); plot3(y1,y2,x) title('繪圖的三維圖形') grid on
空間曲面的繪制
x = [-2:0.2:2]; y = x; [X,Y] = meshgrid(x,y); Z = X.*exp(-X.^2-Y.^2); subplot(2,2,1) % 繪制子圖第一幅 surf(Z); shading flat subplot(2,2,2) % 繪制子圖第二幅 mesh(Z); subplot(2,2,3) % 繪制子圖第三幅 meshc(Z) subplot(2,2,4) % 繪制子圖第四幅 surfl(Z) view(20,7)