MATLAB基本语法 初学者
MATLAB 環(huán)境下的行為就像一個(gè)超級(jí)復(fù)雜的計(jì)算器。您可以使用 >> 命令提示符下輸入命令。
MATLAB?是一種解釋型的環(huán)境。換句話說,你給一個(gè)命令 MATLAB 就馬上執(zhí)行。
實(shí)踐
鍵入一個(gè)有效的表達(dá),例如,
5+5然后按ENTER鍵
當(dāng)點(diǎn)擊“執(zhí)行”按鈕,或者按Ctrl+ E,MATLAB執(zhí)行它立即返回的結(jié)果是:
讓我們使用幾個(gè)例子:
當(dāng)你點(diǎn)擊“執(zhí)行,或者按Ctrl+ E,MATLAB執(zhí)行它立即返回的結(jié)果是:
ans = 9另外一個(gè)例子,
sin(pi /2) % sine of angle 90°當(dāng)你點(diǎn)擊“執(zhí)行”按鈕,或者按Ctrl+ E,MATLAB執(zhí)行它立即返回的結(jié)果是:
ans = 1MATLAB提供了一些特殊的一些數(shù)學(xué)符號(hào)的表達(dá),像圓周率π, Inf for ∞, i (and j) for √-1 etc. nan?代表“不是一個(gè)數(shù)字”。
使用分號(hào)(;)
分號(hào)(;)表示語句結(jié)束。但是,如果想抑制和隱藏 MATLAB 輸出表達(dá),表達(dá)后添加一個(gè)分號(hào)。
例如,
添加注釋
百分比符號(hào)(%)是用于表示一個(gè)注釋行。例如,
x = 9 % assign the value 9 to x也可以寫注釋,使用一塊塊注釋操作符%{%}。
MATLAB編輯器包括工具和上下文菜單項(xiàng),來幫助添加,刪除或更改注釋的格式。
常用的運(yùn)算符和特殊字符
MATLAB支持以下常用的運(yùn)算符和特殊字符:
| + | 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 π |
命名變量
變數(shù)名稱是由一個(gè)字母后由任意數(shù)量的字母,數(shù)字或下劃線。
MATLAB是區(qū)分大小寫的。
變量名可以是任意長度,但是,MATLAB使用只有前N個(gè)字符,其中N是由函數(shù)namelengthmax。
MATLAB 并不需要任何類型的聲明或維度報(bào)表。 MATLAB 每當(dāng)遇到一個(gè)新的變量名稱,創(chuàng)建變量,并分配適當(dāng)?shù)膬?nèi)存空間。
如果變量已經(jīng)存在,則MATLAB替換以新的內(nèi)容的原始內(nèi)容,并分配新的存儲(chǔ)空間,在必要的情況下。
例如,
Total = 42上述語句創(chuàng)建了一個(gè)名為“Total” 的 1-1 矩陣存儲(chǔ)值42。
MATLAB中可用的數(shù)據(jù)類型
MATLAB 提供15個(gè)基本數(shù)據(jù)類型。每種數(shù)據(jù)類型的數(shù)據(jù)存儲(chǔ)在矩陣或陣列的形式。這個(gè)矩陣的大小或陣列是一個(gè)最低 0-0,這可以長大為任何規(guī)模大小的矩陣或數(shù)組。
下表顯示了在 MATLAB 中最常用的數(shù)據(jù)類型:
| 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 |
例子
創(chuàng)建一個(gè)腳本文件,用下面的代碼:
str = 'Hello World!' n = 2345 d = double(n) un = uint32(789.50) rn = 5678.92347 c = int32(rn)上面的代碼編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生以下結(jié)果:
str = Hello World! n =2345 d =2345 un =790 rn =5.6789e+03 c =5679數(shù)據(jù)類型轉(zhuǎn)換
MATLAB 提供各種函數(shù),用于從一種數(shù)據(jù)類型轉(zhuǎn)換到另一種。下表顯示的數(shù)據(jù)類型轉(zhuǎn)換函數(shù):
| 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 |
測定的數(shù)據(jù)類型
MATLAB 提供各種函數(shù)標(biāo)識(shí)數(shù)據(jù)類型的變量。
下表提供了確定一個(gè)變量的數(shù)據(jù)類型的函數(shù):
| 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 |
例子
創(chuàng)建一個(gè)腳本文件,用下面的代碼:
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) 當(dāng)運(yùn)行該文件,它會(huì)產(chǎn)生以下結(jié)果: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管理會(huì)話的命令
MATLAB提供會(huì)話管理的各種命令。下表提供了所有這樣的命令:
| clc | 清除命令窗口。 |
| clear | 從內(nèi)存中刪除變量。 |
| exist | 檢查存在的文件或變量。 |
| global | 聲明變量為全局。 |
| help | 搜索幫助主題。 |
| lookfor | 搜索幫助關(guān)鍵字條目。 |
| quit | 停止MATLAB。 |
| who | 列出當(dāng)前變量。 |
| whos | 列出當(dāng)前變量(長顯示)。 |
使用系統(tǒng)命令
?
MATLAB提供各種有用的命令與系統(tǒng)工作,在工作區(qū)中當(dāng)前的工作,如保存為一個(gè)文件,并加載文件。
它還提供了其他系統(tǒng)相關(guān)的活動(dòng),如各種命令,顯示日期,列出目錄中的文件,顯示當(dāng)前目錄等。
下表顯示了一些常用的系統(tǒng)相關(guān)的命令:
| cd | 改變當(dāng)前目錄。 |
| date | 顯示當(dāng)前日期。 |
| delete | 刪除一個(gè)文件。 |
| diary | 日記文件記錄開/關(guān)切換。 |
| dir | 列出當(dāng)前目錄中的所有文件。 |
| load | 負(fù)載工作區(qū)從一個(gè)文件中的變量。 |
| path | 顯示搜索路徑。 |
| pwd | 顯示當(dāng)前目錄。 |
| save | 保存在一個(gè)文件中的工作區(qū)變量。 |
| type | 顯示一個(gè)文件的??內(nèi)容。 |
| what | 列出所有MATLAB文件在當(dāng)前目錄中。 |
| wklread | 讀取.wk1電子表格文件。? |
輸入和輸出命令
MATLAB提供了以下輸入和輸出相關(guān)的命令:
| disp | 顯示一個(gè)數(shù)組或字符串的內(nèi)容。 |
| fscanf | 閱讀從文件格式的數(shù)據(jù)。 |
| format | 控制屏幕顯示的格式。 |
| fprintf | 執(zhí)行格式化寫入到屏幕或文件。 |
| input | 顯示提示并等待輸入。 |
| ; | 禁止顯示網(wǎng)版印刷 |
fscanf和fprintf命令的行為像C scanf和printf函數(shù)。他們支持格式如下代碼:
| %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. |
用于數(shù)字顯示格式的函數(shù)有以下幾種形式:
| 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. |
向量,矩陣和陣列命令
下表列出了各種命令用于工作數(shù)組,矩陣和向量:
| 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環(huán)境下,每一個(gè)變量是一個(gè)數(shù)組或矩陣。
在一個(gè)簡單的方法,您可以指定變量。例如,
x = 3 % defining x and initializing it with a valueMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
x =3它創(chuàng)建了一個(gè)1-1的矩陣名為x和的值存儲(chǔ)在其元素。讓我們查看另一個(gè)例子,
x = sqrt(16) % defining x and initializing it with an expressionMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
x =4請(qǐng)注意:
-
一旦一個(gè)變量被輸入到系統(tǒng)中,你可以引用它。
-
變量在使用它們之前,必須有值。
-
當(dāng)表達(dá)式返回一個(gè)結(jié)果,不分配給任何變量,系統(tǒng)分配給一個(gè)變量命名ans,以后可以使用。
例如,
sqrt(78)MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
ans =8.8318可以使用這個(gè)變量?ans:
9876/ansMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
ans =1.1182e+03讓我們來看看另一個(gè)例子:
x = 7 * 8; y = x * 7.89MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
y =441.8400多個(gè)賦值
可以有多個(gè)任務(wù)在同一行。例如,
a = 2; b = 7; c = a * bMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
c =14我已經(jīng)忘記了變量!?
who?命令顯示所有已經(jīng)使用的變量名。
whoMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
Your variables are: a ans b c x ywhos?命令顯示多一點(diǎn)有關(guān)變量:
-
當(dāng)前內(nèi)存中的變量
-
每個(gè)變量的類型
-
內(nèi)存分配給每個(gè)變量
-
無論他們是復(fù)雜的變量與否
MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
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命令刪除所有(或指定)從內(nèi)存中的變量(S)。
clear x % it will delete x, won't display anything clear % it will delete all variables in the workspace% peacefully and unobtrusively長任務(wù)
長任務(wù)可以通過使用省略號(hào)(...)延伸到另一條線路。例如,
initial_velocity = 0; acceleration = 9.8; time = 20; final_velocity = initial_velocity ...+ acceleration * timeMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
final_velocity =196格式命令
默認(rèn)情況下,MATLAB 四個(gè)小數(shù)位值顯示數(shù)字。這就是所謂的?short format.
但是,如果想更精確,需要使用 format 命令。
長(long?) 命令格式顯示小數(shù)點(diǎn)后16位。
例如:
format long x = 7 + 10/3 + 5 ^ 1.2MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
x =17.231981640639408另外一個(gè)例子,
format short x = 7 + 10/3 + 5 ^ 1.2MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
x =17.2320空格格式命令回合到小數(shù)點(diǎn)后兩位數(shù)字。例如,
format bank daily_wage = 177.45; weekly_wage = daily_wage * 6MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
weekly_wage =1064.70MATLAB 顯示大量使用指數(shù)表示法。
短格式e命令允許以指數(shù)的形式顯示小數(shù)點(diǎn)后四位,加上指數(shù)。
例如,
format short e 4.678 * 4.9MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
ans =2.2922e+01?format long?e命令允許以指數(shù)的形式顯示小數(shù)點(diǎn)后四位,加上指數(shù)。例如,
format long e x = piMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
x =3.141592653589793e+00format rat?格式大鼠命令給出最接近的有理表達(dá)式,從計(jì)算所得。例如,
format rat 4.678 * 4.9MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
ans =2063/90創(chuàng)建向量
向量是一維數(shù)組中的數(shù)字。 MATLAB允許創(chuàng)建兩種類型的矢量:
-
行向量
-
列向量
創(chuàng)建行向量括在方括號(hào)中的元素的集合,用空格或逗號(hào)分隔的元素。
例如,
r = [7 8 9 10 11]MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
r =Columns 1 through 47 8 9 10 Column 511另外一個(gè)例子,
r = [7 8 9 10 11]; t = [2, 3, 4, 5, 6]; res = r + tMATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
res =Columns 1 through 49 11 13 15 Column 517創(chuàng)建列向量通過內(nèi)附組方括號(hào)中的元素,使用分號(hào)(;)分隔的元素。
c = [7; 8; 9; 10; 11]MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
c =7 8 9 10 11創(chuàng)建矩陣
矩陣是一個(gè)二維數(shù)字陣列。
在MATLAB中,創(chuàng)建一個(gè)矩陣每行輸入空格或逗號(hào)分隔的元素序列,最后一排被劃定一個(gè)分號(hào)。例如,創(chuàng)建一個(gè)3×3的矩陣:
m = [1 2 3; 4 5 6; 7 8 9]MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:
m =1 2 3 4 5 6 7 8 9MATLAB 還允許你寫入到一個(gè)文件中的一系列命令和執(zhí)行文件完整的單元,就像寫一個(gè)函數(shù),并調(diào)用它。
M 文件
MATLAB允許寫兩個(gè)程序文件:
-
腳本 - 腳本文件 .m?擴(kuò)展程序文件。在這些文件中寫的一系列命令,想一起執(zhí)行。腳本不接受輸入和不返回任何輸出。他們在工作區(qū)中的數(shù)據(jù)操作。
-
函數(shù) -函數(shù)文件?.m?擴(kuò)展程序文件。函數(shù)可以接受輸入和返回輸出。內(nèi)部變量是本地的函數(shù)。
可以使用MATLAB 編輯器或其他任何文本編輯器來創(chuàng)建 .m 文件。在本節(jié)中,我們將討論的腳本文件。 MATLAB 命令和函數(shù)調(diào)用的腳本文件包含多個(gè)連續(xù)的行。可以運(yùn)行一個(gè)腳本,在命令行中鍵入其名稱。
創(chuàng)建并運(yùn)行腳本文件
創(chuàng)建腳本文件,需要使用文本編輯器。可以打開 MATLAB 編輯器,可使用兩個(gè)方法:
-
使用命令提示符
-
使用IDE
如果是在命令提示符下使用命令提示符下,鍵入編輯。這將打開編輯器。可以直接鍵入編輯,然后在文件名(?.m?擴(kuò)展程序文件名)
edit Or edit <filename>上面的命令將在默認(rèn)情況下,MATLAB 目錄中創(chuàng)建文件。如果想存儲(chǔ)在一個(gè)特定的文件夾中的所有程序文件,那么一定要提供整個(gè)路徑。
讓我們創(chuàng)建一個(gè)文件夾名為 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如果首次創(chuàng)建的文件,MATLAB 會(huì)提示您進(jìn)行確認(rèn)。單擊“Yes”。
?
另外,如果使用的是IDE,選擇?NEW -> Script。這也打開編輯器,并創(chuàng)建一個(gè)文件名為命名。輸入代碼后可以命名并保存文件。
在編輯器中輸入下面的代碼:
NoOfStudents = 6000; TeachingStaff = 150; NonTeachingStaff = 20; Total = NoOfStudents + TeachingStaff ...+ NonTeachingStaff; disp(Total);創(chuàng)建和保存文件后,可以運(yùn)行在兩個(gè)方面:
-
編輯器窗口中單擊“Run”按鈕或
-
只要在命令提示符下鍵入文件名(不含擴(kuò)展名):>> prog1
命令窗口提示顯示的結(jié)果是:
6170例子
創(chuàng)建一個(gè)腳本文件,然后輸入下面的代碼:
?
a = 5; b = 7; c = a + b d = c + sin(b) e = 5 * d f = exp(-d)?
上面的代碼編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生以下結(jié)果:
c =12 d =12.6570 e =63.2849 f =3.1852e-06歡迎關(guān)注公眾號(hào):算法工程師的學(xué)習(xí)日志
?
總結(jié)
以上是生活随笔為你收集整理的MATLAB基本语法 初学者的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab Retinex图像增强算法
- 下一篇: YOLO系列算法精讲:从yolov1至y