第1章 MATLAB 概述

第1章 MATLAB 概述

1.1 创建变量

>> a=2 % 创建变量

a =

     2

>> whos % 查看变量属性
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double        

>> b=8

b =

     8

>> c=a+b

c =

    10

>> d=tan(a)

d =

   -2.1850

>> e=sin(b)

e =

    0.9894

>> whos
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double        
  b         1x1                 8  double        
  c         1x1                 8  double        
  d         1x1                 8  double        
  e         1x1                 8  double        

1.2 数值显示格式

格式 显示格式 格式效果说明
short 3.1416 默认格式,保留 4 位小数,整数部分超过 3 位的小数用 shortE 格式
shortE 3.1416e+00 用 1 位整数和 4 位小数表示,倍数关系用科学记数法表示成十进制指数形式
shortG 3.1416 保证 5 位有效数字,当为\(10 ^ {-5} \sim 10 ^ 5\) 时,自动调整数位,超出时用 shortE 格式
shortEng 3.1416e+000 短工程记数法,小数点后包含 4 位数,指数为 3 的倍数
long 3.141592653589793 15 位小数,最多 2 位整数,共 16 位十进制数,否则用 longE 格式表示
longE 3.141592653589793e+00 15 位小数的科学记数法
longG 3.14159265358979 保证 15 位有效数字,当为\(10 ^ {-15} \sim 10 ^ {15}\) 时,自动调整数位,超出时用 longE 格式
longEng 3.14159265358979e+000 长工程记数法,包含 15 位有效位数,指数为 3 的倍数
rat 355/113 rational,用分数有理数近似表示
hex 400921fb54442d18 十六进制格式表示
+ + 正 / 负数和零分别用 +、-、空格表示
bank 3.14 限两位小数,用于表示元、角、分
compact 不留空行显示 在显示结果之间没有空行的紧凑格式
loose 留空行显示 在显示结果之间有空行的稀疏格式
>> pi

ans =

    3.1416

>> format long
>> pi

ans =

   3.141592653589793

>> format longE
>> pi

ans =

     3.141592653589793e+00

>> format shortE
>> pi

ans =

   3.1416e+00

>> format % 重置为默认值
>> pi

ans =

    3.1416

>> format compact % 重置为紧凑格式
>> pi
ans =
    3.1416

1.3 函数

新建“函数 funa.m 文件”

function f=funa(var)
f=sin(var);
end
>> type funa.m % 显示函数内容

function f=funa(var)
f=sin(var);
end
>> x=[0 pi/2 pi 3*pi/2 2*pi]

x =

         0    1.5708    3.1416    4.7124    6.2832

>> sinx=funa(x) % 调用函数

sinx =

         0    1.0000    0.0000   -1.0000   -0.0000

1.4 脚本

新建 “脚本 sroot.m 文件”

% sroot 用于求 A*X=b
A=[1 2 1; 2 -1 3; 3 1 2];
b=[7; 7; 18];
X=A\b
>> sroot
错误使用  / 
矩阵维度必须一致。

出错 sroot ( 第 4 行 )
X=A/b
   ^
 
>> sroot

X =

     7
     1
    -2

1.5 函数列表

1.5.1 初等函数列表

>> help elfun
  Elementary math functions.
 
  Trigonometric.
    sin         - Sine.
    sind        - Sine of argument in degrees.
    sinh        - Hyperbolic sine.
    asin        - Inverse sine.
    asind       - Inverse sine, result in degrees.
    asinh       - Inverse hyperbolic sine.
    cos         - Cosine.
    cosd        - Cosine of argument in degrees.
    cosh        - Hyperbolic cosine.
    acos        - Inverse cosine.
    acosd       - Inverse cosine, result in degrees.
    acosh       - Inverse hyperbolic cosine.
    tan         - Tangent.
    tand        - Tangent of argument in degrees.
    tanh        - Hyperbolic tangent.
    atan        - Inverse tangent.
    atand       - Inverse tangent, result in degrees.
    atan2       - Four quadrant inverse tangent.
    atan2d      - Four quadrant inverse tangent, result in degrees.
    atanh       - Inverse hyperbolic tangent.
    sec         - Secant.
    secd        - Secant of argument in degrees.
    sech        - Hyperbolic secant.
    asec        - Inverse secant.
    asecd       - Inverse secant, result in degrees.
    asech       - Inverse hyperbolic secant.
    csc         - Cosecant.
    cscd        - Cosecant of argument in degrees.
    csch        - Hyperbolic cosecant.
    acsc        - Inverse cosecant.
    acscd       - Inverse cosecant, result in degrees.
    acsch       - Inverse hyperbolic cosecant.
    cot         - Cotangent.
    cotd        - Cotangent of argument in degrees.
    coth        - Hyperbolic cotangent.
    acot        - Inverse cotangent.
    acotd       - Inverse cotangent, result in degrees.
    acoth       - Inverse hyperbolic cotangent.
    hypot       - Square root of sum of squares.
    deg2rad     - Convert angles from degrees to radians.
    rad2deg     - Convert angles from radians to degrees.
 
  Exponential.
    exp         - Exponential.
    expm1       - Compute exp(x)-1 accurately.
    log         - Natural logarithm.
    log1p       - Compute log(1+x) accurately.
    log10       - Common (base 10) logarithm.
    log2        - Base 2 logarithm and dissect floating point number.
    pow2        - Base 2 power and scale floating point number.
    realpow     - Power that will error out on complex result.
    reallog     - Natural logarithm of real number.
    realsqrt    - Square root of number greater than or equal to zero.
    sqrt        - Square root.
    nthroot     - Real n-th root of real numbers.
    nextpow2    - Next higher power of 2.
 
  Complex.
    abs         - Absolute value.
    angle       - Phase angle.
    complex     - Construct complex data from real and imaginary parts.
    conj        - Complex conjugate.
    imag        - Complex imaginary part.
    real        - Complex real part.
    unwrap      - Unwrap phase angle.
    isreal      - True for real array.
    cplxpair    - Sort numbers into complex conjugate pairs.
 
  Rounding and remainder.
    fix         - Round towards zero.
    floor       - Round towards minus infinity.
    ceil        - Round towards plus infinity.
    round       - Round towards nearest integer.
    mod         - Modulus (signed remainder after division).
    rem         - Remainder after division.
    sign        - Signum.

1.5.2 高等函数列表

>> help specfun
  Specialized math functions.
 
  Specialized math functions.
    airy        - Airy functions.
    besselj     - Bessel function of the first kind.
    bessely     - Bessel function of the second kind.
    besselh     - Bessel functions of the third kind (Hankel function).
    besseli     - Modified Bessel function of the first kind.
    besselk     - Modified Bessel function of the second kind.
    beta        - Beta function.
    betainc     - Incomplete beta function.
    betaincinv  - Inverse incomplete beta function.
    betaln      - Logarithm of beta function.
    ellipj      - Jacobi elliptic functions.
    ellipke     - Complete elliptic integral.
    erf         - Error function.
    erfc        - Complementary error function.
    erfcx       - Scaled complementary error function.
    erfinv      - Inverse error function.
    erfcinv     - Inverse complementary error function.
    expint      - Exponential integral function.
    gamma       - Gamma function.
    gammainc    - Incomplete gamma function.
    gammaincinv - Inverse incomplete gamma function. 
    gammaln     - Logarithm of gamma function.
    psi         - Psi (polygamma) function.
    legendre    - Associated Legendre function.
    cross       - Vector cross product.
    dot         - Vector dot product.
 
  Number theoretic functions.
    factor      - Prime factors.
    isprime     - True for prime numbers.
    primes      - Generate list of prime numbers.
    gcd         - Greatest common divisor.
    lcm         - Least common multiple.
    rat         - Rational approximation.
    rats        - Rational output.
    perms       - All possible permutations.
    nchoosek    - All combinations of N elements taken K at a time.
    factorial   - Factorial function.
 
  Coordinate transforms.
    cart2sph    - Transform Cartesian to spherical coordinates.
    cart2pol    - Transform Cartesian to polar coordinates.
    pol2cart    - Transform polar to Cartesian coordinates.
    sph2cart    - Transform spherical to Cartesian coordinates.
    hsv2rgb     - Convert hue-saturation-value colors to red-green-blue.
    rgb2hsv     - Convert red-green-blue colors to hue-saturation-value.

1.5.3 矩阵函数列表

>> help elmat
  Elementary matrices and matrix manipulation.
 
  Elementary matrices.
    zeros       - Zeros array.
    ones        - Ones array.
    eye         - Identity matrix.
    repmat      - Replicate and tile array.
    repelem     - Replicate elements of an array.
    combinations- Generate all element combinations of arrays.
    linspace    - Linearly spaced vector.
    logspace    - Logarithmically spaced vector.
    freqspace   - Frequency spacing for frequency response.
    meshgrid    - X and Y arrays for 3-D plots.
    accumarray  - Construct an array with accumulation.
    :           - Regularly spaced vector and index into matrix.
 
  Basic array information.
    size        - Size of array.
    length      - Length of vector.
    ndims       - Number of dimensions.
    numel       - Number of elements.
    disp        - Display matrix or text.
    isempty     - True for empty array.
    isequal     - True if arrays are numerically equal.
    isequaln    - True if arrays are numerically equal, treating NaNs as equal.
    height      - Number of rows.
    width       - Number of columns.
 
  Matrix manipulation.
    cat         - Concatenate arrays.
    reshape     - Reshape array by rearranging existing elements.
    resize      - Resize data by adding or removing elements.
    paddata     - Pad data.
    trimdata    - Trim data.
    diag        - Diagonal matrices and diagonals of matrix.
    blkdiag     - Block diagonal concatenation.
    tril        - Extract lower triangular part.
    triu        - Extract upper triangular part.
    fliplr      - Flip matrix in left/right direction.
    flipud      - Flip matrix in up/down direction.
    flip        - Flip the order of elements.
    rot90       - Rotate matrix 90 degrees.
    :           - Regularly spaced vector and index into matrix.
    find        - Find indices of nonzero elements.
    end         - Last index.
    sub2ind     - Linear index from multiple subscripts.
    ind2sub     - Multiple subscripts from linear index.
    bsxfun      - Binary singleton expansion function.
 
  Multi-dimensional array functions.
    ndgrid      - Generate arrays for N-D functions and interpolation.
    permute     - Permute array dimensions.
    ipermute    - Inverse permute array dimensions.
    shiftdim    - Shift dimensions.
    circshift   - Shift array circularly.
    squeeze     - Remove singleton dimensions.
 
  Array utility functions.
    isscalar    - True for scalar.
    isvector    - True for vector.
    isrow       - True for row vector.
    iscolumn    - True for column vector.
    ismatrix    - True for matrix.
 
  Special variables and constants.
    eps         - Floating point relative accuracy.
    realmax     - Largest positive floating point number.
    realmin     - Smallest positive floating point number.
    intmax      - Largest positive integer value.
    intmin      - Smallest integer value.
    flintmax    - Largest consecutive integer in floating point format.
    pi          - 3.1415926535897....
    i           - Imaginary unit.
    inf         - Infinity.
    nan         - Not-a-Number.
    isnan       - True for Not-a-Number.
    isinf       - True for infinite elements.
    isfinite    - True for finite elements.
    j           - Imaginary unit.
    true        - True array.
    false       - False array.
 
  Specialized matrices.
    compan      - Companion matrix.
    gallery     - Test matrices.
    hadamard    - Hadamard matrix.
    hankel      - Hankel matrix.
    hilb        - Hilbert matrix.
    invhilb     - Inverse Hilbert matrix.
    magic       - Magic square.
    pascal      - Pascal matrix.
    rosser      - Classic symmetric eigenvalue test problem.
    toeplitz    - Toeplitz matrix.
    vander      - Vandermonde matrix.
    wilkinson   - Wilkinson's eigenvalue test matrix.
 
  Controlling multithreading setting.
    maxNumCompThreads - Controls the maximum number of computational threads.

1.6 语句

>> a=11

a =

    11

>> rho=(1+sqrt(a))/2 % 函数 sqrt 求平方根

rho =

    2.1583

>> b=abs(3+8i) % 函数 abs 用于求绝对值或复数的模

b =

    8.5440

>> x=sqrt(besselk(5/3,rho-1)) % besselk 为第二类修正的 Bessel 函数

x =

    0.8931

>> x=sqrt(besselk(5/3,rho-i))

x =

   0.2916 + 0.2398i

1.7 常用命令

命令 命令说明 命令 命令说明
clc 清除命令行窗口中的所有显示内容 cd 显示或改变当前工作目录
clf 清除图形窗口 dir 显示当前目录或指定目录下的文件
clear 清理内存变量 load 加载指定文件的变量
disp 显示变量或文字内容 diary 日志文件命令
exit 退出 MATLAB ! 调用 DOS 命令
quit 退出 MATLAB,等同于 exit pack 收集内存碎片
home 将光标移至命令行窗口的左上角 hold 图形保持开关
echo 命令行窗口信息显示开关 path 显示搜索目录
type 显示指定 M 文件的内容 save 保存内存变量到指定文件
more 控制命令行窗口的分页输出 close 关闭指定图形窗口

1.8 标点符号

名称 符号 功能
空格 变量分隔符:数组行元素分隔符:矩阵一行中各元素间的分隔符:程序语句关键词分隔符
逗号 , 分隔要显示计算结果的各语句:变量分隔符:矩阵一行中各元素间的分隔符:函数参数分隔符
点号 . 数值中的小数点:结构数组的域访问符
分号 ; 分隔不显示计算结果的各语句;矩阵行与行的分隔符
冒号 : 用于生成一维数值数组;表示一维数组的全部元素或多维数组中某一维的全部元素
百分号 % 注释语句说明符,凡在其后的字符均被视为注释性内容而不被执行
单引号 ' 字符串标识符
叹号 ! 调用操作系统运算
续行符 长命令行需要分行时用于连接下行
赋值号 = 将表达式赋值给一个变量
圆括号 () 用于矩阵元素引用:用于函数输入变量列表;确定运算的优先级
方括号 [] 向量和矩阵的标识符;用于函数输出列表
花括号 {} 标识构造元胞数组
下画线 _ 用于变量、函数或文件名中的连字符
at 符 @ 用在函数名前形成函数句柄:用在目录名前形成用户对象类目录

1.9 帮助命令

命令 功能 命令 功能
demo 运行 MATLAB 演示程序 lookfor 按照指定的关键字查找所有相关的 M 文件
help 获取在线帮助 helpwin 运行帮助窗口,列出函数组的主题
who 列出当前工作区窗口中的所有变量 which 显示指定函数或文件的路径
doc 在网络浏览器中显示指定内容的 HTML 格式帮助文件或启动 helpdesk what 列出当前目录或指定目录下的 M 文件、 MAT 文件和 MEX 文件
exist 检查变量、脚本、函数、文件夹或类的存在性 whos 列出当前工作空间中变量的更多信息

1.9.1 help 命令

help name % 显示 name(可以是函数、方法、类、工具箱或变量等)指定的帮助信息
类型名 功能 类型名 功能
general 通用命令 graphics 通用图形函数
elfun 基本数学函数 control 控制系统工具箱函数
elmat 基本矩阵及矩阵操作 ops 操作符及特殊字符
mathfun 矩阵函数、数值线性代数 polyfyn 多项式和内插函数
datafun 数据分析及傅里叶变换 lang 语言结构及调试
strfun 字符串函数 funfun 非线性数值功能函数
iofun 低级文件输入 / 输出函数 ... ...

1.9.2 lookfor 命令

lookfor keyword % 在搜索路径中所有 MATLAB 程序文件的第一个注释行( H1 行)中,搜索指定的关键字,搜索结果显示所有匹配文件的 H1 行
lookfor keyword -all % 搜索 MATLAB 程序文件的第一个完整注释块
posted @ 2026-01-12 08:42  Zhuye_inking  阅读(37)  评论(0)    收藏  举报