日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MATLAB基本语法 初学者

發(fā)布時(shí)間:2025/3/21 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MATLAB基本语法 初学者 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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è)例子:

3 ^ 2 % 3 raised to the power of 2

當(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 = 1

MATLAB提供了一些特殊的一些數(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)算符和特殊字符:

運(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支持以下特殊變量和常量:

NameMeaning
ansMost recent answer.
epsAccuracy of floating-yiibai precision.
i,jThe imaginary unit √-1.
InfInfinity.
NaNUndefined numerical result (not a number).
piThe 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ù)類型:

數(shù)據(jù)類型描述
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

例子

創(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ù):

函數(shù)目的/作用
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

測定的數(shù)據(jù)類型

MATLAB 提供各種函數(shù)標(biāo)識(shí)數(shù)據(jù)類型的變量。

下表提供了確定一個(gè)變量的數(shù)據(jù)類型的函數(shù):

函數(shù)目的/作用
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

例子

創(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ù)。他們支持格式如下代碼:

格式代碼目的/作用
%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.

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

Format函數(shù)最多可顯示
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.

向量,矩陣和陣列命令

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

命令作用/目的
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環(huán)境下,每一個(gè)變量是一個(gè)數(shù)組或矩陣。

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

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

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

x =3

它創(chuàng)建了一個(gè)1-1的矩陣名為x和的值存儲(chǔ)在其元素。讓我們查看另一個(gè)例子,

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

MATLAB將執(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/ans

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

ans =1.1182e+03

讓我們來看看另一個(gè)例子:

x = 7 * 8; y = x * 7.89

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

y =441.8400

多個(gè)賦值

可以有多個(gè)任務(wù)在同一行。例如,

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

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

c =14

我已經(jīng)忘記了變量!?

who?命令顯示所有已經(jīng)使用的變量名。

who

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

Your variables are: a ans b c x y

whos?命令顯示多一點(diǎn)有關(guān)變量:

  • 當(dāng)前內(nèi)存中的變量

  • 每個(gè)變量的類型

  • 內(nèi)存分配給每個(gè)變量

  • 無論他們是復(fù)雜的變量與否

whos

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 double

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

MATLAB將執(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.2

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

x =17.231981640639408

另外一個(gè)例子,

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

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

x =17.2320

空格格式命令回合到小數(shù)點(diǎn)后兩位數(shù)字。例如,

format bank daily_wage = 177.45; weekly_wage = daily_wage * 6

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

weekly_wage =1064.70

MATLAB 顯示大量使用指數(shù)表示法。

短格式e命令允許以指數(shù)的形式顯示小數(shù)點(diǎn)后四位,加上指數(shù)。

例如,

format short e 4.678 * 4.9

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

ans =2.2922e+01?

format long?e命令允許以指數(shù)的形式顯示小數(shù)點(diǎn)后四位,加上指數(shù)。例如,

format long e x = pi

MATLAB將執(zhí)行上面的語句,并返回以下結(jié)果:

x =3.141592653589793e+00

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

format rat 4.678 * 4.9

MATLAB將執(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 + t

MATLAB將執(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 9

MATLAB 還允許你寫入到一個(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。