Matlab 基礎操作

使用版本:Matlab 2016

一、基本運算

有點類似於 python,初始化不用設置數據類型;運算總體更偏向於數學

1、矩陣乘法

>> a=[1 2;1 2]

>> b=[3 4;5 6]

>> a*b
13 16				
13 16

上式就相當於:
[1212][3456]=[13161316] \begin{bmatrix} 1 & 2 \\ 1 & 2 \\ \end{bmatrix} * \begin{bmatrix} 3 & 4 \\ 5 & 6 \\ \end{bmatrix} = \begin{bmatrix} 13 & 16 \\ 13 & 16 \\ \end{bmatrix}

>> a.*b
3 8
5 12

但如果這樣寫就相當於 點對點間 的相乘

二、基本方法

1、清屏是 clc
2、輸出方式 fprintf
3、whileif 後面的語句不用加括號,且都不用加 :

舉例

x = 1;        //分號 可加可不加
if x+2==3
    fprintf('%.2f',x)   //記住用單引號
end           //必須加

4、elseif 要連着寫
5、另一種輸出方式是 disp(其便捷程度有點像 cout )

>> x = 2;
>> disp(x)
2
>> disp('132')
132

6、不等於符號 ~=
7、 a 模 b 就是 mod(a,b)
8、for 循環

for i = 1 : 5
	disp(i)
end

output: 1 2 3 4 5

for i = 1 : -1 : -5
	disp(i)
end

output: 1 0 -1 -2 -3 -4 -5

v = [0,1,2,3,4]
for i = v
	disp(i)
end

output: 0 1 2 3 4

9、求和函數(這個就類似 Excel)

v = [0,1,2,3,4]
sum(v)

output: 10

10、自定義函數(還是和 python 類似)
但區別就在於它每個函數都是獨立一個文件(極致封裝)

function mysum(n) //相當於 void
    s=0;
    for i = 1 : n
        s=i+s;
    end
    disp(s)
end

>> mysum(3)
6

function result = mysum(n)
    s=0;
    for i = 1 : n
        s=i+s;
    end
    result = s;
end

>> a = mysum(3)  //要是沒有分號 程序則不會顯示結果
6

三、基本畫圖

1、y = x

>> x = [1,2,3];
>> y = [1,2,3];
>> plot(x,y)

2、y = x2

>> x = -5 : 0.1 : 5;
>> y1 = x.^2;  //點對點
>> y2 = x.^2;
>> % axis equal  //將 x 與 y 座標變成一樣長(不過這裏註釋掉了)
>> plot(x,y1,'green-o',x,y2,'black')  //綠色關鍵點標記 黑色爲函數圖像

3、可視圖

>> y = [1.0,1.2,2.1,4.6,9.4,15.9];
>> bar(y)
>> x = 2000 : 2006;
>> bar(x,y)

4、3D Graph

>> theta = 0 : pi/50 : 6*pi;  // 6 pi是 360°
>> x = cos(theta);
>> y = sin(theta);
>> z = 0 : 300;
>> plot3(x,y,z)  //表示 3D

四、進階畫圖

1、合併圖像

x = -5 : 0.1 : 5;
y1 = x.^2;  
plot(x,y1,'black')  

hold on;  //合併圖像

x = -5 : 0.1 : 5;
y2 = x.^3;
plot(x,y2,'green')  

grid on;  //添加網格  記住是最後加的
title('x^2 vs x^3');  //添加標題
xlabel('x-x');  // x軸添加描述
ylabel('y-y');  // y軸添加描述

2、分割圖像

x = -4 : 0.1 : 4;

y1 = sin(x);
y2 = sin(2.*x);
y3 = sin(3.*x);
y4 = sin(4.*x);

// 不需要 hold on

subplot(2,2,1);  //圖型分割爲 2:2,選擇第一層
plot(x,y1);
title('y = sin(x)');  //添加標題

subplot(2,2,2);
plot(x,y2);
title('y = sin(2.*x)');

subplot(2,2,3);
plot(x,y3);
title('y = sin(3.*x)');

subplot(2,2,4);
plot(x,y4);
title('y = sin(4.*x)');

3、分割獨立圖像

x = -4 : 0.1 : 4;

y1 = cos(x);
y2 = cos(2.*x);
y4 = cos(4.*x);

subplot(2,2,1);
plot(x,y1);
title('y = cos(x)');

subplot(2,2,2);
plot(x,y2);
title('y = cos(2.*x)');

subplot(2,2,[3,4]);  //將 3、4格按列表的形式組起來
plot(x,y4);
title('y = cos(4.*x)');

4、面圖像

x = -3 : 0.1 : 3;
y = -3 : 0.1 : 3;
[X,Y] = meshgrid(x,y);  //形成一系列對應的點
Z = X.^2 + Y.^2;
surf(X,Y,Z)  //打印出面


x = -3 : 0.1 : 3;
y = -3 : 0.1 : 3;
[X,Y] = meshgrid(x,y);
Z = X.^2 + Y.^2;
plot3(X,Y,Z)  //打印出線
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章