取整、取模、取余函数比较
函数 | 说明 |
---|---|
floor(x) | 向下取整 。floor(2.3)=2; floor(-2.3)=-3; |
ceil(x) | 向上取整。 ceil(2.3)=3; ceil(-2.3)=-2; |
round(x) | 四舍五入到最近的整数。round(4.5)=5; round(-4.5)=-5; |
fix(x) | 向原点靠。fix(-2.5)=-2; fix(2.5)=2; |
mod(x,y) | 取模函数。 |
rem(x,y) | 取余函数。 |
floor(x+0.5) 可以将正数四舍五入,floor(x-0.5)可以将负数四舍五入,实现round()的效果。
取模取余思想相似,区别在于
- 取模的结果符号跟除数一致,如mod(15,-4)=-1,而取余的余数跟被除数一致,mod(15,-4)=3。
- 当被除数x、除数y符号一致时,两个函数结果相同。
- mod(X,Y)取模运算中用的是floor( )函数,rem(X,Y)取余运算中用的是fix( )函数。mod(x,y) is x - n.*y where n = floor(x./y) if y != 0。rem(x,y) is x - n.*y where n = fix(x./y) if y != 0。
- 规定mod(x,0)=x;mod(x,x)=0。rem(x,0)=NaN;rem(x,x),对于x!=0时,为0。
sum函数
A = [ 1 1 2 2 3 3 ] A= \begin{bmatrix} 1 & 1\\ 2 & 2\\ 3 & 3 \end{bmatrix} A=⎣⎡123123⎦⎤
sum(matrix,1) | sum(matrix,2) |
---|---|
sum(A,1) = [ 6 6 ] \begin{bmatrix}6 & 6 \end{bmatrix} [66] | sum(A,2) = [ 2 4 6 ] \begin{bmatrix}2 \\4 \\6\end{bmatrix} ⎣⎡246⎦⎤ |
总结,sum(matrix,1) 对行求和, sum(matrix,2)对列求和