一、norm()
1. 对于Vector,norm返回的是向量的二范数
即:
∣
∣
x
∣
∣
2
=
∑
i
=
1
N
x
i
2
||x||_2= \sqrt{\sum_{i=1}^{N} {x}^{2}_{i} }
∣∣ x ∣ ∣ 2 = i = 1 ∑ N x i 2
Vector2d vec ( 3.0 , 4.0 ) ;
cout << vec. norm ( ) << endl;
/ 输出5
2. 对于Matrix,norm返回的是矩阵的弗罗贝尼乌斯范数(Frobenius Norm)
即:
∣
∣
A
∣
∣
F
=
∑
i
=
1
m
∑
j
=
1
n
∣
x
i
j
∣
2
||A||_F= \sqrt{\sum_{i=1}^{m}\sum_{j=1}^{n} |x_{ij}|^{2} }
∣∣ A ∣ ∣ F = i = 1 ∑ m j = 1 ∑ n ∣ x ij ∣ 2
Matrix2d mat;
mat << 1 , 2
3 , 4 ;
cout << mat. norm ( ) << endl; //输出sqrt(1*1+2*2+3*3+4*4),即sqrt(30) = 5.47723
二、normalize()
清楚了norm()的定义后,normalize()其实就是把自身的各元素除以它的范数,返回值为void。
例如:
vec. normalize ( ) ;
cout << vec << endl; //输出: 0.6
// 0.8
mat. normalize ( ) ; //mat各元素除以mat.norm()
cout << mat << endl;
三、normalized()
而normalized()与normalize()类似,只不过normalize()是在自身上做修改,而normalized()返回的是一个新的Vector/Matrix,并不改变原有的矩阵。
四、测试案例
基本代码
// testing vector
Vector3d vec ( 3 , 4 , 5 ) ;
cout << "norm_using is:\n" << vec. norm ( ) << endl;
vec. normalize ( ) ;
cout << "normalize_using is:\n" << vec << endl;
cout << "normalized_using is:\n" << vec. normalized ( ) << endl;
// testing matrix
Matrix3d mat;
mat << 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ;
cout << "norm_using is:\n" << mat. norm ( ) << endl;
mat. normalize ( ) ;
cout << "normalize_using is:\n" << mat << endl;
cout << "normalized_using is:\n" << mat. normalized ( ) << endl;
测试结果
norm_using is:
7.07107
normalize_using is:
0.424264
0.565685
0.707107
normalized_using is:
0.424264
0.565685
0.707107
norm_using is:
16.8819
normalize_using is:
0.0592349 0.11847 0.177705
0.23694 0.296174 0.355409
0.414644 0.473879 0.533114
normalized_using is:
0.0592349 0.11847 0.177705
0.23694 0.296174 0.355409
0.414644 0.473879 0.533114