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     Attributes

  a         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 4
       7              8              9             10       
  Column 5
      11    

另外一个例子,

r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t

MATLAB将执行上面的语句,并返回以下结果:

res =
  Columns 1 through 4
       9             11             13             15       
  Column 5
      17

创建列向量通过内附组方括号中的元素,使用分号(;)分隔的元素。

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

欢迎关注公众号:算法工程师的学习日志

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值