1、给定一个列向量v1,和一个行向量v2, 计算矩阵M,使得M(i, j) = v1(i) + v2(j)。一种常用的向量化实现:m = length(v1);
n = length(v2);
M = repmat(v1, [1, n]) + repmat(v2, [m, 1]);
2、另外,发现bsxfun是个好东东,其中函数全部用C实现了快速矩阵算法,在时间和空间上都比较节省。
C = bsxfun(fun,A,B)
那个fun可以是以下很多算子。
3、当d很小而n很大的时候,比如对大量2x2矩阵求逆(这在设计几何的问题中很常见),那么直接利用2x2矩阵的求逆共识,进行向量化了:a = reshape(A(1, 1, :), [1, n]);
b = reshape(A(1, 2, :), [1, n]);
c = reshape(A(2, 1, :), [1, n]);
d = reshape(A(2, 2, :), [1, n]);
g = 1 ./ (a .* d - b .* c);
r11 = d .* g;
r12 = -b .* g;
r21 = -c .* g;
r22 = a .* g;
B = reshape([r11; r21; r12; r22], [2, 2, n]);
4、算过优化式子的同学都有经验,输入很多时候都要求0均值或者正定化什么的。其实矩阵论中早有定论:
对于X,直接搞X*X',就可以正定化。当然这里可以用刚才bsxfun来算。零均值的话,我用下面代码搞定的:
meanX = mean(X,1);
meanY = mean(Y,1);
X0 = bsxfun(@minus, X, meanX);
Y0 = bsxfun(@minus, Y, meanY);
n = length(v2);
M = repmat(v1, [1, n]) + repmat(v2, [m, 1]);
2、另外,发现bsxfun是个好东东,其中函数全部用C实现了快速矩阵算法,在时间和空间上都比较节省。
C = bsxfun(fun,A,B)
那个fun可以是以下很多算子。
@plus
|
Plus
|
@minus
|
Minus
|
@times
|
Array multiply
|
@rdivide
|
Right array divide
|
@ldivide
|
Left array divide
|
@power
|
Array power
|
@max
|
Binary maximum
|
@min
|
Binary minimum
|
@rem
|
Remainder after division
|
@mod
|
Modulus after division
|
@atan2
|
Four quadrant inverse tangent
|
@hypot
|
Square root of sum of squares
|
@eq
|
Equal
|
@ne
|
Not equal
|
@lt
|
Less than
|
@le
|
Less than or equal to
|
@gt
|
Greater than
|
@ge
|
Greater than or equal to
|
@and
|
Element-wise logical AND
|
@or
|
Element-wise logical OR
|
@xor
|
Logical exclusive OR
|
b = reshape(A(1, 2, :), [1, n]);
c = reshape(A(2, 1, :), [1, n]);
d = reshape(A(2, 2, :), [1, n]);
g = 1 ./ (a .* d - b .* c);
r11 = d .* g;
r12 = -b .* g;
r21 = -c .* g;
r22 = a .* g;
B = reshape([r11; r21; r12; r22], [2, 2, n]);
4、算过优化式子的同学都有经验,输入很多时候都要求0均值或者正定化什么的。其实矩阵论中早有定论:
对于X,直接搞X*X',就可以正定化。当然这里可以用刚才bsxfun来算。零均值的话,我用下面代码搞定的:
meanX = mean(X,1);
meanY = mean(Y,1);
X0 = bsxfun(@minus, X, meanX);
Y0 = bsxfun(@minus, Y, meanY);
No comments:
Post a Comment