MATLAB基本语法

MATLAB 环境下的行为就像一个超级复杂的计算器。您可以使用 >> 命令提示符下输入命令。

MATLAB 是一种解释型的环境。换句话说,你给一个命令 MATLAB 就马上执行。

实践

键入一个有效的表达,例如,

5 + 5

然后按ENTER键

当点击“执行”按钮,或者按Ctrl+ E,MATLAB执行它立即返回的结果是:

ans = 10

让我们使用几个例子:

3 ^ 2 % 3 raised to the power of 2

当你点击“执行”按钮,或者按Ctrl+ E,MATLAB执行它立即返回的结果是:

ans = 9

另外一个例子,

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

当你点击“执行”按钮,或者按Ctrl+ E,MATLAB执行它立即返回的结果是:

ans = 1

另外一个例子,

7/0 % Divide by zero

当点击“执行”按钮,或者按Ctrl+ E,MATLAB执行它立即返回的结果是:

ans = Inf
warning: division by zero

另外一个例子,

732 * 20.3 

当点击“执行”按钮,或者按Ctrl+ E,MATLAB执行它立即返回的结果是:

ans =  1.4860e+04

MATLAB提供了一些特殊的一些数学符号的表达,像圆周率π, Inf for ∞, i (and j) for √-1 etc. Nan 代表“不是一个数字”。

使用分号(;)

分号(;)表示语句结束。但是,如果想抑制和隐藏 MATLAB 输出表达,表达后添加一个分号。

例如,

x = 3; y = x + 5

当点击“执行”按钮,或者按Ctrl+ E,MATLAB执行它立即返回的结果是:

y =  8

添加注释

百分比符号(%)是用于表示一个注释行。例如,

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 web3.
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支持以下特殊变量和常量:

Name Meaning
ans Most recent answer.
eps Accuracy of floating-web3 precision.
i,j The imaginary unit √-1.
Inf Infinity.
NaN Undefined numerical result (not a number).
pi The number π

命名变量

变数名称是由一个字母后由任意数量的字母,数字或下划线。

MATLAB是区分大小写的。

变量名可以是任意长度,但是,MATLAB使用只有前N个字符,其中N是由函数namelengthmax。

保存你的工作

使用save命令保存在工作区中的所有变量,作为一个文件扩展名为.mat,在当前目录中。 

例如

save myfile

可以随时重新加载该文件后使用load命令。

load myfile
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3