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

Name Meaning
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 π

命名变量

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

MATLAB是区分大小写的。

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

MATLAB 并不需要任何类型的声明或维度报表。 MATLAB 每当遇到一个新的变量名称,创建变量,并分配适当的内存空间。

如果变量已经存在,则MATLAB替换以新的内容的原始内容,并分配新的存储空间,在必要的情况下。

例如,

Total = 42

上述语句创建了一个名为“Total” 的 1-1 矩阵存储值42。

MATLAB中可用的数据类型

MATLAB 提供15个基本数据类型。每种数据类型的数据存储在矩阵或阵列的形式。这个矩阵的大小或阵列是一个最低 0-0,这可以长大为任何规模大小的矩阵或数组。

下表显示了在 MATLAB 中最常用的数据类型:

数据类型 描述
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

例子

创建一个脚本文件,用下面的代码:

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 提供各种函数,用于从一种数据类型转换到另一种。下表显示的数据类型转换函数:

函数 目的/作用
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

测定的数据类型

MATLAB 提供各种函数标识数据类型的变量。

下表提供了确定一个变量的数据类型的函数:

函数 目的/作用
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

例子

创建一个脚本文件,用下面的代码:

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函数。他们支持格式如下代码:

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

用于数字显示格式的函数有以下几种形式:

Format函数 最多可显示
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.

向量,矩阵和阵列命令

下表列出了各种命令用于工作数组,矩阵和向量:

命令 作用/目的
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.
print 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环境下,每一个变量是一个数组或矩阵。

在一个简单的方法,您可以指定变量。例如,

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基本语法 初学者相关推荐

  1. MATLAB常见语法错误分析及解决办法

    1.Subscript indices must either be real positive integers or logicals 中文解释:下标索引必须是正整数类型或者逻辑类型 出错原因:在 ...

  2. MATLAB 数据分析方法(第2版)1.3 MATLAB基本语法

    1.3 MATLAB基本语法 1.3.1 数据类型 MATLAB中的基本数据类型有15种,主要是整型.浮点.逻辑.字符.日期和时间.结构数组.单元格数组以及函数句柄等.不论数据是怎样的类型,在计算机程 ...

  3. matlab乘幂的指数是矩阵,信号与系统MATLAB基本语法.ppt

    信号与系统MATLAB基本语法 第二章 基本语法 2.1 变量及其赋值 2.2 矩阵的初等运算 2.3 元素群运算 2.4 逻辑判断与流程控制 2.5 基本绘图方法 2.6 M文件及程序调试 2.1 ...

  4. matlab基础语法

    %% matlab基础语法% 后面的加分号时,运行结果在命令窗口不显示. % 不加分号时,当点击回车时,运行结果就会立即显示出来!%% 清除 clear all %清除工作区中的所有变量 clc %清 ...

  5. MATLAB基本语法详解

    MATLAB基本语法详解 下面内容 :变量.M-Files.决策.循环容易掌握 命令.数据类型.运算符不需要记住,用了再查 变量 每个MatLab变量可以是数组或者矩阵 最简单的方法指定变量 x = ...

  6. MATLAB基础语法总结

    主体参照:全网最全MATLAB学习归纳总结(建模学习必备) . MATLAB讲解PPT和MATLAB官方帮助文档这里对该教程做一定的完善与汇总 1. MATLAB编辑器常用快捷键 1.1 编辑器窗口操 ...

  7. 编程类-----matlab基础语法复习(1)

    2019年美赛随笔记录: 具体功能:基础语法+基本运算+画图+矩阵+excel读取....... 所遇问题及其解决方案:         1.   que:matlab中plot画图无法复制下来图片? ...

  8. matlab相语法,学会System Generator(10)——支持的MATLAB语法

    本文是该系列的第10篇,上一篇介绍了在System Generator设计中使用MCode模块调用MATLAB代码来完成逻辑控制.本文将介绍System Generator支持的所有MATLAB语法. ...

  9. matlab | 常用语法

    常用语法 if语句 不等式 矩阵的表示 用法一: 用法二: 用法三:查找矩阵最大值max(max()) 用法四:提取某几行到某几列 用法五: 矩阵归一化[0,255] 用法六 等差数列生成 linsp ...

最新文章

  1. python小项目案例-拯救Python新手的几个项目实战
  2. android广告页白屏_android 白屏
  3. 【Java代码】未分页数据根据参数进行分页(粘贴可用)
  4. JEECG开源社区招收学生说明
  5. Linux下服务器搭建(7)——Oracle Linux ISO Images 高速镜像源下载地址(各版本齐全 建议收藏 最后更新2020.07.22)
  6. 手把手叫你玩转网络编程系列之三 完成端口(Completion Port)详解
  7. 二分法求函数方程根的matlab实现(内附例题和代码)
  8. python 自动玩 连连看 外挂
  9. bugku ctf 杂项 旋转跳跃 (熟悉的声音中貌似又隐藏着啥,key:syclovergeek)
  10. mysql 报broken pipe_Mysql Broken pipe错误
  11. 网站seo优化到底该怎么做?
  12. SpringBoot 使用异常自定义错误码
  13. Android 仿soul首页星球旋转,可上下左右方向旋转
  14. 在电信物联网平台实现SOTA远程升级
  15. 基于Java Web技术的动车购票系统
  16. 红旗linux10应用软件,红旗操作系统下载-红旗操作系统v10 官方版下载-6188手游网...
  17. AndroidStudio SSL peer shut down incorrectly 问题
  18. 【TarDAL红外与可见光图像融合论文笔记】
  19. 目前主要的计算机汉字输入方法是什么,计算机汉字输入方法专利_专利申请于2001-03-28_专利查询 - 天眼查...
  20. windows的命令行(CMD)

热门文章

  1. MATLAB句柄相关函数和代码示例(设置美化图表属性)
  2. 清华大学c语言指针ppt,清华大学出版社-C语言10指针.ppt
  3. 《机器学习实践应用》书中源代码
  4. 亿级别记录的mongodb分页查询java代码实现
  5. Hudson-ci/Using Hudson/Installing Hudson/Installing Hudson RPM--官方文档
  6. 机器学习算法基础——数据特征预处理
  7. 【图数据库】史上超全面的Neo4j使用指南
  8. 神经网络贷款风险评估(base on keras and python ) 原创 2017年08月18日 14:35:17 标签: python / 神经网络 / keras 300 用我
  9. 我用 tensorflow 实现的“一个神经聊天模型”:一个基于深度学习的聊天机器人
  10. 这家获得谷歌投资的企业想把亚马逊挑下神坛