如何在Matlab中一次拍摄两个以上矩阵的外部积? [英] How to take outer product of more than two matrices in one shot, in matlab?
问题描述
我要计算y = a⊗a⊗a
,其中a
是n-by-1向量,而⊗
是外部产品运营商.在这种情况下,y
应该是一个n×n×n张量.
I want to compute y = a⊗a⊗a
, where a
is a n-by-1 vector, and ⊗
is the outer product operator. In this case y
should be an n-by-n-by-n tensor.
如果是y = a⊗a
,这很容易.我只是这样做:
If y = a⊗a
, it is easy. I simply do:
y = a * a'
但是在第一种情况下该怎么办?如果存在两个以上的向量,如何在MATLAB中有效地计算该外部乘积?
But what to do in the first case? How do I compute this outer product efficiently in MATLAB if there are more than two vectors?
推荐答案
在y = u⊗v
的多维(张量)情况下,我认为您需要像这样移动第二个操作数的尺寸:
In a multi-dimensional (tensor) case of y = u⊗v
, I believe that you need to shift the dimensions of the second operand like so:
v_t = permute(v, circshift(1:(ndims(u) + ndims(v)), [0, ndims(u)]));
,然后将它们乘以bsxfun
:
y = bsxfun(@times, u, v_t);
常规矩阵乘法仅针对矢量和二维矩阵定义,因此在一般情况下我们不能使用它.
The regular matrix multiplication is defined only for vector and 2-D matrices, so we couldn't use it in the general case.
还要注意,如果第二个操作数是一维矢量,则此计算仍然会失败,因为ndims
对于矢量返回2而不是1.为此,让我们定义自己的计算尺寸的函数:
Also note that this computation still fails if the second operand is a 1-D vector, because ndims
returns 2 instead of 1 for vectors. For this purpose, lets define our own function that counts dimensions:
my_ndims = @(x)(isvector(x) + ~isvector(x) * ndims(x));
要完成答案,您可以定义一个新函数(例如例如一个匿名函数),
To complete the answer, you can define a new function (e.g. an anonymous function), like so:
outprod = @(u, v)bsxfun(@times, u, permute(v, circshift(1:(my_ndims(u) + my_ndims(v)), [0, my_ndims(u)])));
,然后根据需要多次使用.例如,y = a×a×a
的计算方式如下:
and then use it as many times as you want. For example, y = a×a×a
would be computed like so:
y = outprod(outprod(a, a), a);
当然,您可以编写一个更好的函数,该函数接受可变数量的参数以节省输入时间.遵循以下原则:
Of course, you can write a better function that takes a variable number of arguments to save you some typing. Something along these lines:
function y = outprod(u, varargin)
my_ndims = @(x)(isvector(x) + ~isvector(x) * ndims(x));
y = u;
for k = 1:numel(varargin)
v = varargin{k};
v_t = permute(v, circshift(1:(my_ndims(y) + my_ndims(v)),[0, my_ndims(y)]));
y = bsxfun(@times, y, v_t);
end
我希望我数学正确!
这篇关于如何在Matlab中一次拍摄两个以上矩阵的外部积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!