MATLAB基本语法 初学者
MATLAB 環境下的行為就像一個超級復雜的計算器。您可以使用 >> 命令提示符下輸入命令。
MATLAB?是一種解釋型的環境。換句話說,你給一個命令 MATLAB 就馬上執行。
實踐
鍵入一個有效的表達,例如,
5+5然后按ENTER鍵
當點擊“執行”按鈕,或者按Ctrl+ E,MATLAB執行它立即返回的結果是:
讓我們使用幾個例子:
當你點擊“執行,或者按Ctrl+ E,MATLAB執行它立即返回的結果是:
ans = 9另外一個例子,
sin(pi /2) % sine of angle 90°當你點擊“執行”按鈕,或者按Ctrl+ E,MATLAB執行它立即返回的結果是:
ans = 1MATLAB提供了一些特殊的一些數學符號的表達,像圓周率π, Inf for ∞, i (and j) for √-1 etc. nan?代表“不是一個數字”。
使用分號(;)
分號(;)表示語句結束。但是,如果想抑制和隱藏 MATLAB 輸出表達,表達后添加一個分號。
例如,
添加注釋
百分比符號(%)是用于表示一個注釋行。例如,
x = 9 % assign the value 9 to x也可以寫注釋,使用一塊塊注釋操作符%{%}。
MATLAB編輯器包括工具和上下文菜單項,來幫助添加,刪除或更改注釋的格式。
常用的運算符和特殊字符
MATLAB支持以下常用的運算符和特殊字符:
| + | Plus; addition operator. |
| - | Minus; subtraction operator. |
| * | Scalar and matrix multiplication operator. |
| .* | Array multiplication operator. |
| ^ | Scalar and matrix exponentiation operator. |
| .^ | Array exponentiation operator. |
| ? | Left-division operator. |
| / | Right-division operator. |
| . | Array left-division operator. |
| ./ | Array right-division operator. |
| : | Colon; generates regularly spaced elements and represents an entire row or column. |
| ( ) | Parentheses; encloses function arguments and array indices; overrides precedence. |
| [ ] | Brackets; enclosures array elements. |
| . | Decimal yiibai. |
| … | Ellipsis; line-continuation operator |
| , | Comma; separates statements and elements in a row |
| ; | Semicolon; separates columns and suppresses display. |
| % | Percent sign; designates a comment and specifies formatting. |
| _ | Quote sign and transpose operator. |
| ._ | Nonconjugated transpose operator. |
| = | Assignment operator. |
特殊變量和常量
MATLAB支持以下特殊變量和常量:
| ans | Most recent answer. |
| eps | Accuracy of floating-yiibai precision. |
| i,j | The imaginary unit √-1. |
| Inf | Infinity. |
| NaN | Undefined numerical result (not a number). |
| pi | The number π |
命名變量
變數名稱是由一個字母后由任意數量的字母,數字或下劃線。
MATLAB是區分大小寫的。
變量名可以是任意長度,但是,MATLAB使用只有前N個字符,其中N是由函數namelengthmax。
MATLAB 并不需要任何類型的聲明或維度報表。 MATLAB 每當遇到一個新的變量名稱,創建變量,并分配適當的內存空間。
如果變量已經存在,則MATLAB替換以新的內容的原始內容,并分配新的存儲空間,在必要的情況下。
例如,
Total = 42上述語句創建了一個名為“Total” 的 1-1 矩陣存儲值42。
MATLAB中可用的數據類型
MATLAB 提供15個基本數據類型。每種數據類型的數據存儲在矩陣或陣列的形式。這個矩陣的大小或陣列是一個最低 0-0,這可以長大為任何規模大小的矩陣或數組。
下表顯示了在 MATLAB 中最常用的數據類型:
| int8 | 8-bit signed integer |
| uint8 | 8-bit unsigned integer |
| int16 | 16-bit signed integer |
| uint16 | 16-bit unsigned integer |
| int32 | 32-bit signed integer |
| uint32 | 32-bit unsigned integer |
| int64 | 64-bit signed integer |
| uint64 | 64-bit unsigned integer |
| single | single precision numerical data |
| double | double precision numerical data |
| logical | logical values of 1 or 0, represent true and false respectively |
| char | character data (strings are stored as vector of characters) |
| cell array | array of indexed cells, each capable of storing an array of a different dimension and data type |
| structure | C-like structures, each structure having named fields capable of storing an array of a different dimension and data type |
| function handle | yiibaier to a function |
| user classes | objects constructed from a user-defined class |
| java classes | objects constructed from a Java class |
例子
創建一個腳本文件,用下面的代碼:
str = 'Hello World!' n = 2345 d = double(n) un = uint32(789.50) rn = 5678.92347 c = int32(rn)上面的代碼編譯和執行時,它會產生以下結果:
str = Hello World! n =2345 d =2345 un =790 rn =5.6789e+03 c =5679數據類型轉換
MATLAB 提供各種函數,用于從一種數據類型轉換到另一種。下表顯示的數據類型轉換函數:
| char | Convert to character array (string) |
| int2str | Convert integer data to string |
| mat2str | Convert matrix to string |
| num2str | Convert number to string |
| str2double | Convert string to double-precision value |
| str2num | Convert string to number |
| native2unicode | Convert numeric bytes to Unicode characters |
| unicode2native | Convert Unicode characters to numeric bytes |
| base2dec | Convert base N number string to decimal number |
| bin2dec | Convert binary number string to decimal number |
| dec2base | Convert decimal to base N number in string |
| dec2bin | Convert decimal to binary number in string |
| dec2hex | Convert decimal to hexadecimal number in string |
| hex2dec | Convert hexadecimal number string to decimal number |
| hex2num | Convert hexadecimal number string to double-precision number |
| num2hex | Convert singles and doubles to IEEE hexadecimal strings |
| cell2mat | Convert cell array to numeric array |
| cell2struct | Convert cell array to structure array |
| cellstr | Create cell array of strings from character array |
| mat2cell | Convert array to cell array with potentially different sized cells |
| num2cell | Convert array to cell array with consistently sized cells |
| struct2cell | Convert structure to cell array |
測定的數據類型
MATLAB 提供各種函數標識數據類型的變量。
下表提供了確定一個變量的數據類型的函數:
| is | Detect state |
| isa | Determine if input is object of specified class |
| iscell | Determine whether input is cell array |
| iscellstr | Determine whether input is cell array of strings |
| ischar | Determine whether item is character array |
| isfield | Determine whether input is structure array field |
| isfloat | Determine if input is floating-yiibai array |
| ishghandle | True for Handle Graphics object handles |
| isinteger | Determine if input is integer array |
| isjava | Determine if input is Java object |
| islogical | Determine if input is logical array |
| isnumeric | Determine if input is numeric array |
| isobject | Determine if input is MATLAB object |
| isreal | Check if input is real array |
| isscalar | Determine whether input is scalar |
| isstr | Determine whether input is character array |
| isstruct | Determine whether input is structure array |
| isvector | Determine whether input is vector |
| class | Determine class of object |
| validateattributes | Check validity of array |
| whos | List variables in workspace, with sizes and types |
例子
創建一個腳本文件,用下面的代碼:
x = 3 isinteger(x) isfloat(x) isvector(x) isscalar(x) isnumeric(x)x = 23.54 isinteger(x) isfloat(x) isvector(x) isscalar(x) isnumeric(x)x = [1 2 3] isinteger(x) isfloat(x) isvector(x) isscalar(x)x = 'Hello' isinteger(x) isfloat(x) isvector(x) isscalar(x) isnumeric(x) 當運行該文件,它會產生以下結果:x =3 ans =0 ans =1 ans =1 ans =1 ans =1 x =23.5400 ans =0 ans =1 ans =1 ans =1 ans =1 x =1 2 3 ans =0 ans =1 ans =1 ans =0 x = Hello ans =0 ans =0 ans =1 ans =0 ans =0管理會話的命令
MATLAB提供會話管理的各種命令。下表提供了所有這樣的命令:
| clc | 清除命令窗口。 |
| clear | 從內存中刪除變量。 |
| exist | 檢查存在的文件或變量。 |
| global | 聲明變量為全局。 |
| help | 搜索幫助主題。 |
| lookfor | 搜索幫助關鍵字條目。 |
| quit | 停止MATLAB。 |
| who | 列出當前變量。 |
| whos | 列出當前變量(長顯示)。 |
使用系統命令
?
MATLAB提供各種有用的命令與系統工作,在工作區中當前的工作,如保存為一個文件,并加載文件。
它還提供了其他系統相關的活動,如各種命令,顯示日期,列出目錄中的文件,顯示當前目錄等。
下表顯示了一些常用的系統相關的命令:
| cd | 改變當前目錄。 |
| date | 顯示當前日期。 |
| delete | 刪除一個文件。 |
| diary | 日記文件記錄開/關切換。 |
| dir | 列出當前目錄中的所有文件。 |
| load | 負載工作區從一個文件中的變量。 |
| path | 顯示搜索路徑。 |
| pwd | 顯示當前目錄。 |
| save | 保存在一個文件中的工作區變量。 |
| type | 顯示一個文件的??內容。 |
| what | 列出所有MATLAB文件在當前目錄中。 |
| wklread | 讀取.wk1電子表格文件。? |
輸入和輸出命令
MATLAB提供了以下輸入和輸出相關的命令:
| disp | 顯示一個數組或字符串的內容。 |
| fscanf | 閱讀從文件格式的數據。 |
| format | 控制屏幕顯示的格式。 |
| fprintf | 執行格式化寫入到屏幕或文件。 |
| input | 顯示提示并等待輸入。 |
| ; | 禁止顯示網版印刷 |
fscanf和fprintf命令的行為像C scanf和printf函數。他們支持格式如下代碼:
| %s | Format as a string. |
| %d | Format as an integer. |
| %f | Format as a floating yiibai value. |
| %e | Format as a floating yiibai value in scientific notation. |
| %g | Format in the most compact form: %f or %e. |
| ? | Insert a new line in the output string. |
| ? | Insert a tab in the output string. |
用于數字顯示格式的函數有以下幾種形式:
| format short | Four decimal digits (default). |
| format long | 16 decimal digits. |
| format short e | Five digits plus exponent. |
| format long e | 16 digits plus exponents. |
| format bank | Two decimal digits. |
| format + | Positive, negative, or zero. |
| format rat | Rational approximation. |
| format compact | Suppresses some line feeds. |
| format loose | Resets to less compact display mode. |
向量,矩陣和陣列命令
下表列出了各種命令用于工作數組,矩陣和向量:
| cat | Concatenates arrays. |
| find | Finds indices of nonzero elements. |
| length | Computes number of elements. |
| linspace | Creates regularly spaced vector. |
| logspace | Creates logarithmically spaced vector. |
| max | Returns largest element. |
| min | Returns smallest element. |
| prod | Product of each column. |
| reshape | Changes size. |
| size | Computes array size. |
| sort | Sorts each column. |
| sum | Sums each column. |
| eye | Creates an identity matrix. |
| ones | Creates an array of ones. |
| zeros | Creates an array of zeros. |
| cross | Computes matrix cross products. |
| dot | Computes matrix dot products. |
| det | Computes determinant of an array. |
| inv | Computes inverse of a matrix. |
| pinv | Computes pseudoinverse of a matrix. |
| rank | Computes rank of a matrix. |
| rref | Computes reduced row echelon form. |
| cell | Creates cell array. |
| celldisp | Displays cell array. |
| cellplot | Displays graphical representation of cell array. |
| num2cell | Converts numeric array to cell array. |
| deal | Matches input and output lists. |
| iscell | Identifies cell array. |
繪圖命令
MATLAB提供了大量的命令,繪制圖表。下表列出了一些常用的命令繪制:
| axis | Sets axis limits. |
| fplot | Intelligent plotting of functions. |
| grid | Displays gridlines. |
| plot | Generates xy plot. |
| Prints plot or saves plot to a file. | |
| title | Puts text at top of plot. |
| xlabel | Adds text label to x-axis. |
| ylabel | Adds text label to y-axis. |
| axes | Creates axes objects. |
| close | Closes the current plot. |
| close all | Closes all plots. |
| figure | Opens a new figure window. |
| gtext | Enables label placement by mouse. |
| hold | Freezes current plot. |
| legend | Legend placement by mouse. |
| refresh | Redraws current figure window. |
| set | Specifies properties of objects such as axes. |
| subplot | Creates plots in subwindows. |
| text | Places string in figure. |
| bar | Creates bar chart. |
| loglog | Creates log-log plot. |
| polar | Creates polar plot. |
| semilogx | Creates semilog plot. (logarithmic abscissa). |
| semilogy | Creates semilog plot. (logarithmic ordinate). |
| stairs | Creates stairs plot. |
| stem | Creates stem plot. |
在MATLAB環境下,每一個變量是一個數組或矩陣。
在一個簡單的方法,您可以指定變量。例如,
x = 3 % defining x and initializing it with a valueMATLAB將執行上面的語句,并返回以下結果:
x =3它創建了一個1-1的矩陣名為x和的值存儲在其元素。讓我們查看另一個例子,
x = sqrt(16) % defining x and initializing it with an expressionMATLAB將執行上面的語句,并返回以下結果:
x =4請注意:
-
一旦一個變量被輸入到系統中,你可以引用它。
-
變量在使用它們之前,必須有值。
-
當表達式返回一個結果,不分配給任何變量,系統分配給一個變量命名ans,以后可以使用。
例如,
sqrt(78)MATLAB將執行上面的語句,并返回以下結果:
ans =8.8318可以使用這個變量?ans:
9876/ansMATLAB將執行上面的語句,并返回以下結果:
ans =1.1182e+03讓我們來看看另一個例子:
x = 7 * 8; y = x * 7.89MATLAB將執行上面的語句,并返回以下結果:
y =441.8400多個賦值
可以有多個任務在同一行。例如,
a = 2; b = 7; c = a * bMATLAB將執行上面的語句,并返回以下結果:
c =14我已經忘記了變量!?
who?命令顯示所有已經使用的變量名。
whoMATLAB將執行上面的語句,并返回以下結果:
Your variables are: a ans b c x ywhos?命令顯示多一點有關變量:
-
當前內存中的變量
-
每個變量的類型
-
內存分配給每個變量
-
無論他們是復雜的變量與否
MATLAB將執行上面的語句,并返回以下結果:
Name Size Bytes Class Attributesa 1x1 8 double ans 1x1 8 double b 1x1 8 double c 1x1 8 double x 1x1 8 double y 1x1 8 doubleclear命令刪除所有(或指定)從內存中的變量(S)。
clear x % it will delete x, won't display anything clear % it will delete all variables in the workspace% peacefully and unobtrusively長任務
長任務可以通過使用省略號(...)延伸到另一條線路。例如,
initial_velocity = 0; acceleration = 9.8; time = 20; final_velocity = initial_velocity ...+ acceleration * timeMATLAB將執行上面的語句,并返回以下結果:
final_velocity =196格式命令
默認情況下,MATLAB 四個小數位值顯示數字。這就是所謂的?short format.
但是,如果想更精確,需要使用 format 命令。
長(long?) 命令格式顯示小數點后16位。
例如:
format long x = 7 + 10/3 + 5 ^ 1.2MATLAB將執行上面的語句,并返回以下結果:
x =17.231981640639408另外一個例子,
format short x = 7 + 10/3 + 5 ^ 1.2MATLAB將執行上面的語句,并返回以下結果:
x =17.2320空格格式命令回合到小數點后兩位數字。例如,
format bank daily_wage = 177.45; weekly_wage = daily_wage * 6MATLAB將執行上面的語句,并返回以下結果:
weekly_wage =1064.70MATLAB 顯示大量使用指數表示法。
短格式e命令允許以指數的形式顯示小數點后四位,加上指數。
例如,
format short e 4.678 * 4.9MATLAB將執行上面的語句,并返回以下結果:
ans =2.2922e+01?format long?e命令允許以指數的形式顯示小數點后四位,加上指數。例如,
format long e x = piMATLAB將執行上面的語句,并返回以下結果:
x =3.141592653589793e+00format rat?格式大鼠命令給出最接近的有理表達式,從計算所得。例如,
format rat 4.678 * 4.9MATLAB將執行上面的語句,并返回以下結果:
ans =2063/90創建向量
向量是一維數組中的數字。 MATLAB允許創建兩種類型的矢量:
-
行向量
-
列向量
創建行向量括在方括號中的元素的集合,用空格或逗號分隔的元素。
例如,
r = [7 8 9 10 11]MATLAB將執行上面的語句,并返回以下結果:
r =Columns 1 through 47 8 9 10 Column 511另外一個例子,
r = [7 8 9 10 11]; t = [2, 3, 4, 5, 6]; res = r + tMATLAB將執行上面的語句,并返回以下結果:
res =Columns 1 through 49 11 13 15 Column 517創建列向量通過內附組方括號中的元素,使用分號(;)分隔的元素。
c = [7; 8; 9; 10; 11]MATLAB將執行上面的語句,并返回以下結果:
c =7 8 9 10 11創建矩陣
矩陣是一個二維數字陣列。
在MATLAB中,創建一個矩陣每行輸入空格或逗號分隔的元素序列,最后一排被劃定一個分號。例如,創建一個3×3的矩陣:
m = [1 2 3; 4 5 6; 7 8 9]MATLAB將執行上面的語句,并返回以下結果:
m =1 2 3 4 5 6 7 8 9MATLAB 還允許你寫入到一個文件中的一系列命令和執行文件完整的單元,就像寫一個函數,并調用它。
M 文件
MATLAB允許寫兩個程序文件:
-
腳本 - 腳本文件 .m?擴展程序文件。在這些文件中寫的一系列命令,想一起執行。腳本不接受輸入和不返回任何輸出。他們在工作區中的數據操作。
-
函數 -函數文件?.m?擴展程序文件。函數可以接受輸入和返回輸出。內部變量是本地的函數。
可以使用MATLAB 編輯器或其他任何文本編輯器來創建 .m 文件。在本節中,我們將討論的腳本文件。 MATLAB 命令和函數調用的腳本文件包含多個連續的行。可以運行一個腳本,在命令行中鍵入其名稱。
創建并運行腳本文件
創建腳本文件,需要使用文本編輯器。可以打開 MATLAB 編輯器,可使用兩個方法:
-
使用命令提示符
-
使用IDE
如果是在命令提示符下使用命令提示符下,鍵入編輯。這將打開編輯器。可以直接鍵入編輯,然后在文件名(?.m?擴展程序文件名)
edit Or edit <filename>上面的命令將在默認情況下,MATLAB 目錄中創建文件。如果想存儲在一個特定的文件夾中的所有程序文件,那么一定要提供整個路徑。
讓我們創建一個文件夾名為 progs。在命令提示符處鍵入以下命令(>>):
mkdir progs % create directory progs under default directory chdir progs % changing the current directory to progs edit prog1.m % creating an m file named prog1.m如果首次創建的文件,MATLAB 會提示您進行確認。單擊“Yes”。
?
另外,如果使用的是IDE,選擇?NEW -> Script。這也打開編輯器,并創建一個文件名為命名。輸入代碼后可以命名并保存文件。
在編輯器中輸入下面的代碼:
NoOfStudents = 6000; TeachingStaff = 150; NonTeachingStaff = 20; Total = NoOfStudents + TeachingStaff ...+ NonTeachingStaff; disp(Total);創建和保存文件后,可以運行在兩個方面:
-
編輯器窗口中單擊“Run”按鈕或
-
只要在命令提示符下鍵入文件名(不含擴展名):>> prog1
命令窗口提示顯示的結果是:
6170例子
創建一個腳本文件,然后輸入下面的代碼:
?
a = 5; b = 7; c = a + b d = c + sin(b) e = 5 * d f = exp(-d)?
上面的代碼編譯和執行時,它會產生以下結果:
c =12 d =12.6570 e =63.2849 f =3.1852e-06歡迎關注公眾號:算法工程師的學習日志
?
總結
以上是生活随笔為你收集整理的MATLAB基本语法 初学者的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab Retinex图像增强算法
- 下一篇: matlab RBF 神经网络拟合