Skip to main content

Introduction to MATLAB MATLAB 簡介

What is it? 它是什麼?

  • A humble origin: an interactive matrix calculator for students. Now more than 1 million users 一個不起眼的出身:一個面向學生的交互式矩陣計算器。現在超過 100 萬用戶
  • Used in engineering, science, and economics, etc. 用於工程、科學和經濟等領域
  • "A high-level technical computing language and interactive environment for algorithm development, data visualization, data analysis, and numerical computation." - Matworks

Why MATLAB? 為什麼是 MATLAB?

  • Faster algorithm development than other languages 比其他語言更快的算法開發
  • Concise matrix notation and great matrix manipulation. 簡潔的矩陣符號和優秀的矩陣操作
  • Easy visualisation, debugging and code optimisation. 簡單的視覺化、調試和代碼優化
  • Many core mathematical, engineering, and scientific functions built-in. 多種內置的核心數學、工程和科學功能
  • Widely used in education and good community support. Example: Stanford's Machine learning module used Matlab/Octave 在教育中廣泛使用,並有良好的社區支持。例如:斯坦福的機器學習模塊使用 Matlab/Octave

Free Matlab and GNU Octave 下載 Matlab 和 GNU Octave

  • Problem of Matlab: expensive commercial software Matlab 的問題:昂貴的商業軟件
  • Solution 1: Use UoB's Matlab site license 使用 UoB 的 Matlab 站點許可證
  • Solution 2: GNU Octave, an open-source alternative to Matlab, download it from here GNU Octave,一個 Matlab 的開源替代品,從這裡下載

The most useful command in MATLAB 最有用的命令

>> help

or Google

The heart of MATLAB: matrices 矩陣是 MATLAB 的核心

  • MATLAB stands for "matrix laboratory". MATLAB 代表"矩陣實驗室"。
  • The basic data type is matrix (including vectors). 基本數據類型是矩陣(包括向量)。
  • Matrix operations: create, access, modify and manipulate matrices 矩陣操作:創建、訪問、修改和操作矩陣
  • Matrix operation is very fast in MATLAB - try to avoid for-loops 矩陣操作在 MATLAB 中非常快 - 嘗試避免 for 循環

Creating Matrices 創建矩陣

  • Create an empty matrix: 創建一個空矩陣: >> A = []
  • Enter data directly: 直接輸入數據: >> A = [1 1; 2 3; 4 5]
  • If you know the pattern of your matrix: 如果你知道矩陣的模式: >> A = [1:2:100]
  • A lot of functions to create specific matrices: zeros()zeros(), ones()ones(), rand()rand(), eye()eye() 等等。很多函數可以創建特定的矩陣:zeros()zeros()ones()ones()rand()rand()eye()eye() 等等。
  • Let's try code examples (Matrix creation) 讓我們嘗試代碼示例(矩陣創建)

Transposing and concatenating matrices 轉置和串聯矩陣

  • To transpose matrix A, use the transpose operator ' 要轉置矩陣 A,請使用轉置運算符 ' >> B = A'

  • To concatenate matrix, enclose them inside of square brackets. 要連接矩陣,請將它們括在方括號內。 >> C = [A; 6 7]

Indexing 索引

To extract individual entries from a matrix, use indices inside round brackets: 要從矩陣中提取單個條目,請使用圓括號內的索引:

>> A(1,2)

Use the : operator to extract all entries along a certain dimension: 使用 : 操作符來提取某個維度上的所有條目:

>> A(1,:)

Use end statement to get the last index of a dimension: 使用 end 來獲取某個維度的最後一個索引:

>> A(end,1)

Use logical indexing to nd specific entries: 使用邏輯索引來查找特定的條目:

>> A(A>2)

We can also use find() function to nd specific entries: 我們也可以使用 find() 函數來查找特定的條目:

>> A(find(A>2))

Assignment and deletion 賦值和刪除

To change entries in the matrix, using indexing to specify the entries and assign new values: 要更改矩陣中的條目,使用索引來指定條目並賦予新值:

>> A(1,2) = 100

>> A(:,1:3:end) = 100

To delete entries, assign [] : 要刪除條目,賦值 []

>> A(1,:) = []

For a matrix, you can only delete column(s) or row(s) 對於矩陣,只能刪除列或行。

For array (1D matrix), you can delete any entries. 對於數組(1D 矩陣),可以刪除任何條目。

>> A(3) = []

Sorting 排序

We can also sort the elements in a matrix, by default in an ascending order (i.e., from small to large). 我們還可以將矩陣中的元素排序,默認情況下是按升序排序(即從小到大)。

For example, to sort an array: >> A = [9 0 -7 5 3 8 -10 4 2] >> B = sort(A)

For example, to sort a matrix by row, i.e., to sort each of its rows in ascending order: >> A = [3 6 5; 7 -2 4; 1 0 -9] >> B = sort(A,2)

You can also get the arrangement of the elements of A into B along the sorted dimension, i.e., the index of the sorted element of the previous unsorted matrix: >> A = [9 0 -7 5 3 8 -10 4 2] >> [B, idx] = sort(A) 也可以得到 A 的元素在 B 中沿排序維度的排列,即前一個未排序矩陣的排序元素的索引: >> A = [9 0 -7 5 3 8 -10 4 2] >> [B, idx] = sort(A)

Matrix manipulations 矩陣操作

We can perform matrix addition, subtraction, multiplication, exponentiation, etc. 我們可以進行矩陣加法、減法、乘法、指數等操作。

For example, matrix multiplication of an m-by-n matrix and an n-by-p matrix yielding an m-by-p matrix: 例如,m-by-n 矩陣和 n-by-p 矩陣的矩陣乘法產生 m-by-p 矩陣:

>> C = A*B

We can do element-wise matrix arithmetic by using `.' precede the arithmetic operator 我們可以使用"."來進行逐元素矩陣運算。在算術運算符之前

>> A = rand(3,3) >> B = rand(3,3) >> D = A.*B

For element-wise arithmetic operation, both matrices must be the same size. 逐元素算術運算,兩個矩陣必須是相同的大小。

Flow of Control 流程控制

MATLAB only has the following statements: MATLAB 只有以下語句:

  • if, else, elseif
  • switch statements
  • for loops
  • while loops
  • try/catch statements

Scripts and functions 腳本和函數

  • We can use MATLAB editor to edit/save/load/exceute your programs. 我們可以使用 MATLAB 編輯器來編輯/保存/加載/執行您的程序。
  • Two types of MATLAB programs: scripts and functions. 兩種類型的 MATLAB 程序:腳本和函數。
  • A script is a collection of Matlab commands. 腳本是一系列 Matlab 命令的集合。
  • The commands in the script are executed exactly as at the command prompt. 腳本中的命令按照在命令提示符中的方式來執行。
  • However, scripts: 但是,腳本:
    • No lexical scoping, that is, the variables in scripts are global. We cannot reuse the same variable name multiple times. 沒有語法作用域,也就是說,腳本中的變量是全局的。我們不能多次使用相同的變量名稱。
    • Cannot be parameterize to be called multiple times with different inputs. 不能將腳本參數化,以便多次使用不同的輸入調用。
    • Difficult to read and understand. 難以閱讀和理解。
    • Slow. 慢。

Creating functions 創建函數

  • Open a new le in MATLAB editor, or type: edit filename.m at the command prompt. 在 MATLAB 編輯器中打開一個新的 le,或者在命令提示符中輸入:edit filename.m
  • In you m le, begin by creating the function header: function [output1 ,output2, output3...] = myfunction(input1, input2...) 在你的 m le 中,首先創建函數標頭:function [output1 ,output2, output3...] = myfunction(input1, input2...)
  • We can use the inputs as local variables. All variables are local in a function. 我們可以將輸入作為本地變量。函數中的所有變量都是本地的。
  • We must assign values to each of the outputs before the function terminates. 在函數終止之前,我們必須為每個輸出分配值。
  • Although optional, it is better to end the function with the "end" keyword to make the code more readable. 雖然可選,但最好使用"end"關鍵字來使代碼更具可讀性。
  • Let's try code examples (MATLAB function example). 讓我們嘗試代碼示例(MATLAB 函數示例)。

Functions: other issues 函數:其他問題

  • The functions must located in the directories of the command path, or under the current working directory. 函數必須位於命令路徑的目錄中,或者位於當前工作目錄下。
  • Use "%" for comments in the function. 在函數中使用"%"進行註釋。
  • We can have multiple functions in a .m le and call them by name. 我們可以在 .m le 中有多個函數,並通過名稱調用它們。
  • We can pass functions as inputs to other functions by creating handle to the function and then pass the handle as a variable. 我們可以通過創建函數的句柄,然後將句柄作為變量傳遞給其他函數,來將函數作為輸入傳遞給其他函數。 >> x = fminbnd(@humps, 0.3, 1)
  • We can create anonymous functions without having to store your function to a le each time: 每次都不需要將函數存儲到 le 中,我們可以創建匿名函數: >> fhandle = @(arglist) expr>> sqr = @(x) x.\*x;

1D/2D plots 1D/2D 繪圖

  • To plot 1D and 2D data, we use plot(y). 繪製 1D 和 2D 數據,我們使用 plot(y)。
  • If y is a vector: a piecewise linear graph of the elements of y versus the index of the elements of y 如果 y 是向量:y 的元素與 y 的元素索引的分段線性圖
  • If y is a matrix: plot(y) will automatically cycle through a predefined (but customizable) list of colors to allow discrimination among sets of data 如果 y 是矩陣:plot(y) 將自動循環遍歷一個預定義的(但可自定義)顏色列表,以允許在數據集之間進行區分
  • If we specify two vectors as arguments, plot(x,y) produces a graph of y versus x. 如果我們將兩個向量作為參數指定,plot(x,y) 將生成一個 y 與 x 的圖。
  • Use hold on command to superimpose all the plots onto the same figure. Use hold off to disable. 使用 hold on 命令將所有繪圖叠加到同一個圖形中。使用 hold off 來禁用。

3D plots 3D 繪圖

  • To plot 3D lines: plot3(X1,Y1,Z1) 繪製 3D 線:plot3(X1,Y1,Z1)
  • To plot 3D shaded surface: surf(X,Y,Z) 繪製 3D 陰影表面:surf(X,Y,Z)
  • You can also specified shading property: shading at/faceted/interp
  • To plot 3D mesh: mesh(X,Y,Z) 繪製 3D 網格:mesh(X,Y,Z)
  • To plot contour lines: contourf(X,Y,Z) 繪製輪廓線:contourf(X,Y,Z)

Customise plots 自定義繪圖

  • Multiple subfigures: subplot(nr,nc,i)
  • Title: title('you title')
  • Axis labels: xlabel('x'); ylabel('y'); zlabel('z')
  • We need to get handle of a gure
    • Handle of the current gure: gcf()
    • Handle of the current set of axes: gca()
  • To access specific properties: get(handle,'property')
  • To change specific properties: set(handle,'property1', value1, 'property2', value2, ...)