[英]Multiply each row of a matrix with its transposed self
The formula I have to translate to Octave/Matlab goes something like this:我必须转换为 Octave/Matlab 的公式是这样的:
\sum (v_i - m) (v_i - m)^T
I have a matrix, and I need to take each row, subtract m
from it and then multiply it with its own transpose.我有一个矩阵,我需要取每一行,从中减去
m
,然后乘以它自己的转置。 I wrote the inner part as a function:我把内部部分写成一个函数:
function w = str(v, m)
y = v - m
w = y * transpose(y)
end
My matrix is like this我的矩阵是这样的
xx = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
Now I have no idea how to apply this function to each row in a matrix and then sum them up to a new matrix.现在我不知道如何将此函数应用于矩阵中的每一行,然后将它们相加为一个新矩阵。 Maybe someone can help me here.
也许有人可以在这里帮助我。
EDIT: The result is not the dot product.编辑:结果不是点积。 I'm looking for
v * v^T
, which has a matrix as result!我正在寻找
v * v^T
,结果是一个矩阵!
Probably you need this可能你需要这个
X = bsxfun( @minus, A, m );
Y = X'* X;
You can subtract the mean using bsxfun
您可以使用
bsxfun
减去平均值
>> v_m = bsxfun( @minus, v, m );
For the sum of outer product of all vectors you can use bsxfun
again对于所有向量的外积之和,您可以再次使用
bsxfun
>> op = bsxfun( @times, permute( v, [3 1 2]), permute( v, [1 3 2] ) );
>> op = sum( op, 3 );
Suppose the matrix is A, then the solution is假设矩阵是A,那么解是
total = sum(sum((A-m).*(A-m),2));
A.*A
is an element wise multiplication, hence sum(A.*A,2)
returns a column vector, with each element being the self dot product of each row in A
. A.*A
是逐元素乘法,因此sum(A.*A,2)
返回一个列向量,每个元素都是A
中每一行的自点积。
If m is a vector then, it is slightly more complicated.如果 m 是一个向量,那么它稍微复杂一些。
[p,~]=size(A); total = sum(sum((A-repmat(m,p,1)).*(A-repmat(m,p,1)),2));
Cheers.干杯。
In the end, I wrote this:最后,我写了这个:
function w = str(v, m)
y = v - m;
w = y' * y;
end
y = zeros(5,5);
for i=1:12
y = y + str(A(i,:), m);
end
Surely not the most elegant way to do this, but it seems to work.当然不是最优雅的方式来做到这一点,但它似乎工作。
There are two ways to solve this issue:有两种方法可以解决这个问题:
Assume A
is your matrix:假设
A
是你的矩阵:
sum(drag(A' * A))
will do the job.会做的工作。 However, it is slightly more efficient with the following:
但是,它在以下方面的效率稍高一些:
sum((A .* A)(:))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.