Matlab矢量化:如何避免这种“为".环形? [英] Matlab Vectorization : How to avoid this "for" loop?
问题描述
我有以下矩阵:
X=1 2 3
Y=4 5 6
A=1 2 3
4 5 6
7 8 9
我想做
for each (i,j) in A
v = A(i,j)*X - Y
B(i,j) = v * v'
即A的每个元素都乘以向量X,然后所得向量从其自身减去Y,最后我们取该向量的内积以得出单个数字.
可以不用for循环吗?
i.e. each element of A is multiplied by vector X, then resultant vector subtracts Y from itself and finally we take inner product of that vector to bring a single number.
Can it be done without for loop ?
推荐答案
在Matlab中经常忘记的一件事:运算符'
采用转置的共轭(.'
是普通的转置).换句话说,A' == conj(trans(A))
,而A.' == trans(A)
,如果A
是复数矩阵,则会有所不同.
One thing often forgotten in Matlab: The operator '
takes the conjugate transposed (.'
is the ordinary transposed). In other words, A' == conj(trans(A))
, whereas A.' == trans(A)
, which makes a difference if A
is a complex matrix.
好的,让我们将一些数学应用于方程式.我们有
Ok, let's apply some mathematics to your equations. We have
v = A(i,j)*X - Y
B(i,j) = v * v'
= (A(i,j)*X - Y) * (A(i,j)*X - Y)'
= A(i,j)*X * conj(A(i,j))*X' - Y * conj(A(i,j))*X'
- A(i,j)*X * Y' + Y * Y'
= A(i,j)*conj(A(i,j)) * X*X' - conj(A(i,j)) * Y*X' - A(i,j) * X*Y' + Y*Y'
第一个结果将是
B = A.*conj(A) * (X*X') - conj(A) * (Y*X') - A * (X*Y') + Y*Y'
对于实矩阵/向量,一个具有身份
X*Y' == Y*X'
A == conj(A)
这意味着您可以将表达式简化为
which means, you can reduce the expression to
B = A.*A * (X*X') - 2*A * (X*Y') + Y*Y'
= A.^2 * (X*X') - 2*A * (X*Y') + Y*Y'
这篇关于Matlab矢量化:如何避免这种“为".环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!