Skip to main content

MATLAB Advanced Topics MATLAB 高級主題

Character Arrays (Strings) 字符數組(字符串)

  • Character Arrays are character matrices. 字符數組是字符矩陣。 A = 'This is a String.'B = A(1:5)C = [A ; A]
  • char() and abs(): convert from integers to the ascii equivalents and vice versa. char()abs():從整數轉換為 ascii 等效值,反之亦然。 A = char(48)B = abs('String')
  • num2str() and mat2str(): generate string representations of numeric matrices. 生成數字矩陣的字符串表示。
  • str2num(): parse a number from a string 從字符串中解析數字
  • sprintf() and fprintf(): format strings. 格式化字符串。
  • strcmp() and strcmpi(): Compare strings (case sensitive/insensitive) 比較字符串(區分大小寫/不區分大小寫)
  • strfind(): nd the occurrences of one substring inside another. 在另一個子字符串內查找子字符串的出現。

Cell arrays 單元數組

  • A more general and power data structure than matrices. 比矩陣更一般和強大的數據結構。

  • The same cell array can hold elements of different types: 數組可以包含不同類型的元素:

    • numeric matrices of different sizes; 數字矩陣的不同大小;
    • character arrays of different sizes and shapes; 字符數組的不同大小和形狀;
    • other cells; 其他單元;
    • structs; 結構體;
    • objects. 對象。

    B = {[1,2,3],'hello',1;[3;5],'yes','no'}

  • To create a new cell array: 創建新的單元數組:

    A = cell(2,4)

Indexing cell arrays 單元數組索引

  • One important concept: A n-by-m cell array is made up of n×mn \times m, 1-by-1 cell arrays,

  • Two ways to index into and assign into a cell array:

    • () brackets: access or assign cells; Cell = B(1,2)

    • {} brackets: access or assign the data within those cells. String = B{1,2}

  • We must be very careful what kind of brackets we use. Which one is better? 我們必須非常小心我們使用什麼樣的支架。哪一個更好?

    B(1,2) = {'test'} B{1,2} = 'test' B{1,2} = {'test'}

Operating cell arrays 單元數組操作

  • We can operate cell arrays just as matrices, e.g., transpose, reshape,replicate, concatenate, and delete. 我們可以像矩陣一樣操作單元數組,例如轉置,重塑,複製,連接和刪除。

  • cellfun(): to apply a function to the data inside every cell: 對每個單元內的數據應用函數:

    A = {'A', 'test', 'message', 'Which'} [nrows, ncols] = cellfun(@size, A)

  • We can convert between matrices and cell arrays using num2cell(), mat2cell(), and cell2mat(). 我們可以使用 num2cell()mat2cell()cell2mat() 在矩陣和單元數組之間轉換。

Set Operations 集合操作

  • Matrices and cell arrays can be operated as sets or multisets.
  • Set operation functions: union(), intersect(), setdiff(), setxor(), and ismember().
  • unique(): extract the unique elements of a cell array or matrix. uniqueNums = unique([1,2,1,1,2,3,4,4,5,3,2,1])uniqueNames = unique(f'Bob','Fred','Bob','Ed'g)

Putting all together: a worked example 將所有東西放在一起:一個工作例子

Let's analyse William Shakespeare's Hamlet: 讓我們分析威廉·莎士比亞的《哈姆雷特》:

  • How many unique words? 有多少唯一的單詞?
  • What are the most frequent words? 最常見的單詞是什麼?

Structs 結構體

  • Organize data and access it by name { use it as a simple database. Similar to cell arrays, structs store elements of different types. 結構體用於組織數據並通過名稱訪問它們(將其用作簡單的數據庫)。類似於單元數組,結構體存儲不同類型的元素。
  • We can also add/remove fields: 我們還可以添加/刪除字段: S = struct('name','shan','matrix',[1 1; 2 2])S.nameS.newField = 'foo'S = rmfield(S,'matrix')
  • Structs can be stored in cell arrays and matrices. 結構體可以存儲在單元數組和矩陣中。
  • We can access elds by strings, useful in runtime: 我們可以通過字符串訪問字段,這在運行時很有用: fieldname = 'name'distance = S.(fieldname)

Struct arrays 結構體數組

  • Struct array: an array of structs all having the same eldnames 結構數組:所有具有相同字段名的結構數組 S = struct('name',fg,'Salary',fg)S(1) = struct('name','Shan','Salary',100)S(2) = struct('name','Volka','Salary',300)
  • Eectively can be seen as a table:
    • To access a record of elds (row): S(1)
    • To access a column of elds:
    • To access a eld: S(1).name
  • We can convert between cell arrays and struct arrays: cell2struct() and struct2cell()

Hash tables: 哈希表

  • Hash tables map keys to values by hash function. Two parts:

    • Key: a string or numeric scalar
    • Value: anything

    k = {'UK', 'Italy', 'China'} v = {'London', 'Rome', 'Beijing'} CapitalsMap = containers.Map(k, v)

  • To list all keys and values by keys() and values()

  • To add new entry: CapitalsMap('USA') = 'Washington D.C.'

  • To retrieve values: CapitalsMap('USA') values(CapitalsMap, {'USA', 'Italy'})

Debugging 調試

  • keyboard(): add the it anywhere in your m-file to stop at that point. Type return to continue 將它添加到您的 m 文件中的任何位置以在該點停止。輸入返回以繼續
  • Use break points: step one line at a time, continue on until the next break point, or exit debug mode 使用斷點:一次一行,繼續直到下一個斷點,或者退出調試模式
  • dbstop: Set breakpoints for debugging: 設置斷點以進行調試:
    • dbstop if error: stops execution at the rst run-time error that occurs outside a try-catch block. 停止在 try-catch 块之外發生的第一個運行時錯誤時執行。
    • dbstop if naninf: stops if there is an infinite value (Inf) or a value that is not a number (NaN) 如果存在無限值 (Inf) 或非數字值 (NaN),則停止
    • dbstop if EXPRESSION: stops if EXPRESSION evaluates to true 如果 EXPRESSION 計算為 true,則停止

Object Oriented Programming (OOP) in MATLAB 物件導向程式設計(OOP)在 MATLAB 中

  • Q1: What is OOP? 物件導向程式設計(OOP)是什麼?

  • A1: Design of programmes using "objects". 使用「物件」設計程式。

  • Q2: What is objects? 物件是什麼?

  • A2: Data structures that encapsulate data elds and methods that interact with each other via the object's interface. 封裝數據字段和與該對象介面互動的方法的數據結構。

  • Q3: When to use OOP? 何時使用 OOP?

  • A3: When "the number of functions becomes large, designing and managing the data passed to functions becomes difficult and error prone". 當「函數的數量變大,設計和管理傳遞給函數的數據變得困難且容易出錯」時。

OOP in MATLAB: an example MATLAB 中的 OOP:示例

  • Before seeing the example, some important concepts: 在看到示例之前,一些重要的概念:

    • Class: A kind of prototype, or specication for the construction of a objects of a certain class. 類:一種原型,或者某種類的對象構造的規範。
    • Objects: Instances of a class. 物件:類的實例。
    • Properties: Fields that store data. 屬性:存儲數據的字段。
    • Methods: The operations we want to perform on the data. 方法:我們想在數據上執行的操作。
  • You can download my OOP example at here. 你可以在這裡下載我的 OOP 示例。

  • You can learn more from MathWorks' Introduction to Object-Oriented Programming in MATLAB

Building MATLAB Graphical User Interfaces (GUIs) 建立 MATLAB 圖形用戶界面(GUI)

  • MATLAB GUI: a gure window providing pictorial interface to a program. MATLAB GUI:提供圖形界面的圖形窗口以供程序使用。
  • Two ways of building GUIs: 兩種建立 GUI 的方法:
    • GUIDE (GUI Development Environment). GUIDE(GUI 開發環境)。
    • Create m-les that generate GUIs as functions or scripts 創建將 GUI 生成為函數或腳本的 m 文件
  • useful links: 有用的鏈接:

Code optimisation: where to optimise 代碼優化:優化的地方

  • Generally MATLAB is slower than C/JAVA, but it is not always the case. 一般來說,MATLAB 比 C / JAVA 慢,但這並不是一定的。
  • Optimise bottlenecks in your code. 優化您的代碼中的瓶頸。
  • To identify bottlenecks we need to prole the code: profile on/off 為了識別瓶頸,我們需要分析代碼:分析開/關
  • To view the prole: profile viewer 查看分析結果
  • Timing your code: use tic before your code and toc afterwords 為您的代碼計時:在您的代碼之前使用 tic,在代碼之後使用 toc

Code optimisation: techniques 代碼優化:技術

  • Pre-allocate memory: 預分配內存
  • Vectorisation: making your code work on array-structured data in parallel, rather than using for-loops. Visit MathWorks' Code Vectorization Guide 矢量化:讓您的代碼並行處理數組結構數據,而不是使用 for 循環。訪問 MathWorks 的 代碼向量化指南
  • Use built-in functions 使用內置函數
  • Some useful functions for vectorisation: 一些有用的向量化函數:
  • Finally, if you cannot vectorise your code, write it in C/C++ and call them using MEX (See Matworks' tutorial here) 最後,如果您無法向量化您的代碼,請使用 C / C++ 編寫它們,然後使用 MEX 調用它們(在這裡查看 Matworks 的教程