本文说一下Matlab
中表达式的创建,其实也可以理解为函数调用的过程。Matlab
中有变量、数字、各种运算符、函数,这些都可以用在表达式中。你可以认为表达式是一个计算语句或者逻辑语句。下面,直接开始从各个方面入手,介绍Matlab
表达式的创建方式。
Matlab变量
与大多数其他编程语言一样,MATLAB®
语言提供数学表达式,但与大多数编程语言不同的是,这些表达式涉及整个矩阵。
MATLAB
不需要任何类型声明或维度说明。当MATLAB
遇到新的变量名称时,它会自动创建变量,并分配适当大小的存储。如果此变量已存在,MATLAB
会更改其内容,并根据需要分配新存储。例如:
>> num_students = 25
num_students =
25
创建一个名为num_students
的 1×1 矩阵,并将值 25 存储在该矩阵的单一元素中。要查看分配给任何变量的矩阵,只需输入变量名称即可。
变量名称包括一个字母,后面可以跟随任意数目的字母、数字或下划线。MATLAB
区分大小写;它可以区分大写和小写字母。A
和a
不是相同变量。
尽管变量名称可以为任意长度,MATLAB
仅使用名称的前N
个字符(其中N
是函数namelengthmax
返回的数字),并忽略其余字符。因此,很重要的一点是,应使每个变量名称的前N
个字符保持唯一,以便MATLAB
能够区分变量。
>> N = namelengthmax
N =
63
Matlab数字
MATLAB
使用传统的十进制记数法以及可选的小数点和前导加号或减号来表示数字。科学记数法使用字母e
来指定10
次方的缩放因子。虚数使用i
或j
作为后缀。下面给出了合法数字的一些示例:
3 -99 0.0001 9.6397238 1.60210e-20 6.02252e23 1i -3.14159j 3e5i
MATLAB使用IEEE®浮点标准规定的long
格式在内部存储所有数字。浮点数的有限精度约为16位有效小数位数,有限范围约为10-308至10+308。
以双精度格式表示的数字的最大精度为52位。任何需要52位以上的双精度数字都会损失一定精度。例如,下面的代码因截断而将两个不相等的值显示为相等:
>> x = 36028797018963968;
>> y = 36028797018963972;
>> x == y
ans =
1
整数的可用精度为8
位、16
位、32
位和64
位。将相同数字存储为64位整数会保留精度:
>> x = uint64(36028797018963968);
>> y = uint64(36028797018963972);
>> x == y
ans =
0
MATLAB
软件存储复数的实部和虚部。该软件根据上下文采用不同方法来处理各个部分的量值。例如,sort
函数根据量值进行排序,如果量值相等,则根据相位角度排序。
>> sort([3+4i, 4+3i])
ans =
4.0000 + 3.0000i 3.0000 + 4.0000i
这是由相位角度所致:
>> angle(3+4i)
ans =
0.9273
>> angle(4+3i)
ans =
0.6435
“等于”关系运算符==
要求实部和虚部相等。其他二进制关系运算符>
、<
、>=
和<=
忽略数字的虚部,而仅考虑实部。
Matlab矩阵运算符
表达式使用大家熟悉的算术运算符和优先法则。
+ | 加法 |
- | 减法 |
* | 乘法 |
/ | 除法 |
\ | 左除 |
^ | 幂 |
' | 复共轭转置 |
( ) | 指定计算顺序 |
Matlab数组运算符
如果矩阵不用于线性代数运算,则成为二维数值数组。数组的算术运算按元素执行。这意味着,加法和减法运算对数组和矩阵都是相同的,但乘法运算不相同。MATLAB
的乘法数组运算表示法中包含点,也就是小数点。
运算符列表包括
+ | 加法 |
- | 减法 |
.* | 逐元素乘法 |
./ | 逐元素除法 |
.\ | 逐元素左除 |
.^ | 逐元素幂 |
.' | 非共轭数组转置 |
如果使用数组乘法将丢勒的幻方矩阵自乘,则会生成一个数组,该数组包含介于1
至16
之间的整数的平方,并且以不常见的顺序排列:
>> A=magic(4);
>> A.*A
ans =
256 4 9 169
25 121 100 64
81 49 36 144
16 196 225 1
>> A
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
构建表
数组运算对构建表非常有用。假定n
为列向量,构建一个平方和2次幂的表:
>> n = (0:9)';
>> pows = [n n.^2 2.^n]
pows =
0 0 1
1 1 2
2 4 4
3 9 8
4 16 16
5 25 32
6 36 64
7 49 128
8 64 256
9 81 512
初等数学函数逐元素处理数组元素。这里构建一个对数表:
>> format short g
>> x = (1:0.1:2)';
>> logs = [x log10(x)]
logs =
1 0
1.1 0.041393
1.2 0.079181
1.3 0.11394
1.4 0.14613
1.5 0.17609
1.6 0.20412
1.7 0.23045
1.8 0.25527
1.9 0.27875
2 0.30103
Matlab函数
MATLAB
提供了大量标准初等数学函数,包括abs
、sqrt
、exp
和sin
。生成负数的平方根或对数不会导致错误;系统会自动生成相应的复数结果。MATLAB
还提供了许多其他高等数学函数,包括贝塞尔函数和gamma
函数。其中的大多数函数都接受复数参数。有关初等数学函数的列表,请键入help elfun
:会给出所有初等函数列表,我们可以继续help
对应的函数来了解该函数的用法。
>> 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.
有关更多高等数学函数和矩阵函数的列表,请键入help specfun
以及help elmat
。
高等函数列表:
>> 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.
矩阵函数列表:
>> 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.
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.
Matrix manipulation.
cat - Concatenate arrays.
reshape - Reshape array.
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.
某些函数(例如,sqrt
和sin
)是内置函数。内置函数是MATLAB
核心的一部分,因此这些函数非常高效,但计算详细信息是不可访问的。其他函数使用MATLAB
编程语言实现,因此可以访问其计算详细信息。
内置函数与其他函数之间存在一些差异。例如,对于内置函数,您看不到代码。对于其他函数,您可以看到代码,甚至可以根据需要修改代码。
一些特殊函数提供了有用的常量值。
pi | 3.14159265… |
i | 虚数单位 √−1 |
j | 与 i 相同 |
eps | 浮点相对精度 ε=2−52 |
realmin | 最小浮点数 2−1022 |
realmax | 最大浮点数 (2−ε)21023 |
Inf | 无穷 |
NaN | 非数字 |
通过将非零值除以零或计算明确定义的溢出(即超过realmax
)的数学表达式,会生成无穷值。通过尝试计算 0/0
或Inf
–Inf
等没有明确定义的数值的表达式,会生成非数字。
函数名称不会保留。您可以使用如下新变量覆盖任何函数名称:
eps = 1.e-6
并在后续计算中使用该值。可以使用以下命令恢复原始函数
>> clear eps
>> eps
ans =
2.2204e-16
Matlab表达式示例
您已经学习了MATLAB
表达式的几个示例。下面是一些其他示例及生成的值:
>> rho = (1+sqrt(5))/2
rho =
1.618
>> a = abs(3+4i)
a =
5
>> z = sqrt(besselk(4/3,rho-i))
z =
0.37301 + 0.32137i
>> huge = exp(log(realmax))
huge =
1.7977e+308
>> toobig = pi*huge
toobig =
Inf
转载文章,原文出处:MathWorks官网,由古哥整理发布
如若转载,请注明出处:https://iymark.com/articles/2911.html