日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

MATLAB基本语法 初学者

發布時間:2025/3/21 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MATLAB基本语法 初学者 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

MATLAB 環境下的行為就像一個超級復雜的計算器。您可以使用 >> 命令提示符下輸入命令。

MATLAB?是一種解釋型的環境。換句話說,你給一個命令 MATLAB 就馬上執行。

實踐

鍵入一個有效的表達,例如,

5+5

然后按ENTER鍵

當點擊“執行”按鈕,或者按Ctrl+ E,MATLAB執行它立即返回的結果是:


讓我們使用幾個例子:

3 ^ 2 % 3 raised to the power of 2

當你點擊“執行,或者按Ctrl+ E,MATLAB執行它立即返回的結果是:

ans = 9

另外一個例子,

sin(pi /2) % sine of angle 90°

當你點擊“執行”按鈕,或者按Ctrl+ E,MATLAB執行它立即返回的結果是:

ans = 1

MATLAB提供了一些特殊的一些數學符號的表達,像圓周率π, 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支持以下特殊變量和常量:

NameMeaning
ansMost recent answer.
epsAccuracy of floating-yiibai precision.
i,jThe imaginary unit √-1.
InfInfinity.
NaNUndefined numerical result (not a number).
piThe number π

命名變量

變數名稱是由一個字母后由任意數量的字母,數字或下劃線。

MATLAB是區分大小寫的。

變量名可以是任意長度,但是,MATLAB使用只有前N個字符,其中N是由函數namelengthmax。

MATLAB 并不需要任何類型的聲明或維度報表。 MATLAB 每當遇到一個新的變量名稱,創建變量,并分配適當的內存空間。

如果變量已經存在,則MATLAB替換以新的內容的原始內容,并分配新的存儲空間,在必要的情況下。

例如,

Total = 42

上述語句創建了一個名為“Total” 的 1-1 矩陣存儲值42。

MATLAB中可用的數據類型

MATLAB 提供15個基本數據類型。每種數據類型的數據存儲在矩陣或陣列的形式。這個矩陣的大小或陣列是一個最低 0-0,這可以長大為任何規模大小的矩陣或數組。

下表顯示了在 MATLAB 中最常用的數據類型:

數據類型描述
int88-bit signed integer
uint88-bit unsigned integer
int1616-bit signed integer
uint1616-bit unsigned integer
int3232-bit signed integer
uint3232-bit unsigned integer
int6464-bit signed integer
uint6464-bit unsigned integer
singlesingle precision numerical data
doubledouble precision numerical data
logicallogical values of 1 or 0, represent true and false respectively
charcharacter data (strings are stored as vector of characters)
cell arrayarray of indexed cells, each capable of storing an array of a different dimension and data type
structureC-like structures, each structure having named fields capable of storing an array of a different dimension and data type
function handleyiibaier to a function
user classesobjects constructed from a user-defined class
java classesobjects 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 提供各種函數,用于從一種數據類型轉換到另一種。下表顯示的數據類型轉換函數:

函數目的/作用
charConvert to character array (string)
int2strConvert integer data to string
mat2strConvert matrix to string
num2strConvert number to string
str2doubleConvert string to double-precision value
str2numConvert string to number
native2unicodeConvert numeric bytes to Unicode characters
unicode2nativeConvert Unicode characters to numeric bytes
base2decConvert base N number string to decimal number
bin2decConvert binary number string to decimal number
dec2baseConvert decimal to base N number in string
dec2binConvert decimal to binary number in string
dec2hexConvert decimal to hexadecimal number in string
hex2decConvert hexadecimal number string to decimal number
hex2numConvert hexadecimal number string to double-precision number
num2hexConvert singles and doubles to IEEE hexadecimal strings
cell2matConvert cell array to numeric array
cell2structConvert cell array to structure array
cellstrCreate cell array of strings from character array
mat2cellConvert array to cell array with potentially different sized cells
num2cellConvert array to cell array with consistently sized cells
struct2cellConvert structure to cell array

測定的數據類型

MATLAB 提供各種函數標識數據類型的變量。

下表提供了確定一個變量的數據類型的函數:

函數目的/作用
isDetect state
isaDetermine if input is object of specified class
iscellDetermine whether input is cell array
iscellstrDetermine whether input is cell array of strings
ischarDetermine whether item is character array
isfieldDetermine whether input is structure array field
isfloatDetermine if input is floating-yiibai array
ishghandleTrue for Handle Graphics object handles
isintegerDetermine if input is integer array
isjavaDetermine if input is Java object
islogicalDetermine if input is logical array
isnumericDetermine if input is numeric array
isobjectDetermine if input is MATLAB object
isrealCheck if input is real array
isscalarDetermine whether input is scalar
isstrDetermine whether input is character array
isstructDetermine whether input is structure array
isvectorDetermine whether input is vector
classDetermine class of object
validateattributesCheck validity of array
whosList 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函數。他們支持格式如下代碼:

格式代碼目的/作用
%sFormat as a string.
%dFormat as an integer.
%fFormat as a floating yiibai value.
%eFormat as a floating yiibai value in scientific notation.
%gFormat in the most compact form: %f or %e.
?Insert a new line in the output string.
?Insert a tab in the output string.

用于數字顯示格式的函數有以下幾種形式:

Format函數最多可顯示
format shortFour decimal digits (default).
format long16 decimal digits.
format short eFive digits plus exponent.
format long e16 digits plus exponents.
format bankTwo decimal digits.
format +Positive, negative, or zero.
format ratRational approximation.
format compactSuppresses some line feeds.
format looseResets to less compact display mode.

向量,矩陣和陣列命令

下表列出了各種命令用于工作數組,矩陣和向量:

命令作用/目的
catConcatenates arrays.
findFinds indices of nonzero elements.
lengthComputes number of elements.
linspaceCreates regularly spaced vector.
logspaceCreates logarithmically spaced vector.
maxReturns largest element.
minReturns smallest element.
prodProduct of each column.
reshapeChanges size.
sizeComputes array size.
sortSorts each column.
sumSums each column.
eyeCreates an identity matrix.
onesCreates an array of ones.
zerosCreates an array of zeros.
crossComputes matrix cross products.
dotComputes matrix dot products.
detComputes determinant of an array.
invComputes inverse of a matrix.
pinvComputes pseudoinverse of a matrix.
rankComputes rank of a matrix.
rrefComputes reduced row echelon form.
cellCreates cell array.
celldispDisplays cell array.
cellplotDisplays graphical representation of cell array.
num2cellConverts numeric array to cell array.
dealMatches input and output lists.
iscellIdentifies cell array.

繪圖命令

MATLAB提供了大量的命令,繪制圖表。下表列出了一些常用的命令繪制:

命令作用/目的
axisSets axis limits.
fplotIntelligent plotting of functions.
gridDisplays gridlines.
plotGenerates xy plot.
printPrints plot or saves plot to a file.
titlePuts text at top of plot.
xlabelAdds text label to x-axis.
ylabelAdds text label to y-axis.
axesCreates axes objects.
closeCloses the current plot.
close allCloses all plots.
figureOpens a new figure window.
gtextEnables label placement by mouse.
holdFreezes current plot.
legendLegend placement by mouse.
refreshRedraws current figure window.
setSpecifies properties of objects such as axes.
subplotCreates plots in subwindows.
textPlaces string in figure.
barCreates bar chart.
loglogCreates log-log plot.
polarCreates polar plot.
semilogxCreates semilog plot. (logarithmic abscissa).
semilogyCreates semilog plot. (logarithmic ordinate).
stairsCreates stairs plot.
stemCreates stem plot.

在MATLAB環境下,每一個變量是一個數組或矩陣。

在一個簡單的方法,您可以指定變量。例如,

x = 3 % defining x and initializing it with a value

MATLAB將執行上面的語句,并返回以下結果:

x =3

它創建了一個1-1的矩陣名為x和的值存儲在其元素。讓我們查看另一個例子,

x = sqrt(16) % defining x and initializing it with an expression

MATLAB將執行上面的語句,并返回以下結果:

x =4

請注意:

  • 一旦一個變量被輸入到系統中,你可以引用它。

  • 變量在使用它們之前,必須有值。

  • 當表達式返回一個結果,不分配給任何變量,系統分配給一個變量命名ans,以后可以使用。

例如,

sqrt(78)

MATLAB將執行上面的語句,并返回以下結果:

ans =8.8318

可以使用這個變量?ans:

9876/ans

MATLAB將執行上面的語句,并返回以下結果:

ans =1.1182e+03

讓我們來看看另一個例子:

x = 7 * 8; y = x * 7.89

MATLAB將執行上面的語句,并返回以下結果:

y =441.8400

多個賦值

可以有多個任務在同一行。例如,

a = 2; b = 7; c = a * b

MATLAB將執行上面的語句,并返回以下結果:

c =14

我已經忘記了變量!?

who?命令顯示所有已經使用的變量名。

who

MATLAB將執行上面的語句,并返回以下結果:

Your variables are: a ans b c x y

whos?命令顯示多一點有關變量:

  • 當前內存中的變量

  • 每個變量的類型

  • 內存分配給每個變量

  • 無論他們是復雜的變量與否

whos

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 double

clear命令刪除所有(或指定)從內存中的變量(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 * time

MATLAB將執行上面的語句,并返回以下結果:

final_velocity =196

格式命令

默認情況下,MATLAB 四個小數位值顯示數字。這就是所謂的?short format.

但是,如果想更精確,需要使用 format 命令。

長(long?) 命令格式顯示小數點后16位。

例如:

format long x = 7 + 10/3 + 5 ^ 1.2

MATLAB將執行上面的語句,并返回以下結果:

x =17.231981640639408

另外一個例子,

format short x = 7 + 10/3 + 5 ^ 1.2

MATLAB將執行上面的語句,并返回以下結果:

x =17.2320

空格格式命令回合到小數點后兩位數字。例如,

format bank daily_wage = 177.45; weekly_wage = daily_wage * 6

MATLAB將執行上面的語句,并返回以下結果:

weekly_wage =1064.70

MATLAB 顯示大量使用指數表示法。

短格式e命令允許以指數的形式顯示小數點后四位,加上指數。

例如,

format short e 4.678 * 4.9

MATLAB將執行上面的語句,并返回以下結果:

ans =2.2922e+01?

format long?e命令允許以指數的形式顯示小數點后四位,加上指數。例如,

format long e x = pi

MATLAB將執行上面的語句,并返回以下結果:

x =3.141592653589793e+00

format rat?格式大鼠命令給出最接近的有理表達式,從計算所得。例如,

format rat 4.678 * 4.9

MATLAB將執行上面的語句,并返回以下結果:

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 + t

MATLAB將執行上面的語句,并返回以下結果:

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 9

MATLAB 還允許你寫入到一個文件中的一系列命令和執行文件完整的單元,就像寫一個函數,并調用它。

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基本语法 初学者的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。