有效地计算外部产品的3D矩阵-MATLAB [英] Efficiently compute a 3D matrix of outer products - MATLAB

查看:108
本文介绍了有效地计算外部产品的3D矩阵-MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的元素矩阵:

Suppose I have a matrix of elements like so:

A = reshape(1:25, 5, 5)

A =

 1     6    11    16    21
 2     7    12    17    22
 3     8    13    18    23
 4     9    14    19    24
 5    10    15    20    25

我想有效地计算外部乘积的3D矩阵,以使此输出矩阵的第i th 切片是I th 列的外部乘积A本身.如果uv都是列向量,则两个向量uv之间的外部乘积就是u*v.'.

I would like to efficiently compute a 3D matrix of outer products, such that the ith slice of this output matrix is the outer product of the ith column of A with itself. The outer product between two vectors u and v is simply u*v.' if u and v are both column vectors.

因此,此输出矩阵B的每个切片的结构应如下:

Therefore, each slice of this output matrix B should be structured such that:

B(:,:,1) = A(:,1) * A(:,1).';
B(:,:,2) = A(:,2) * A(:,2).';
        ...
        ...
B(:,:,5) = A(:,5) * A(:,5).';

我当前的方法如下.我尝试使用arrayfuncell2mat这样操作:

My current method is the following. I tried doing it this way using arrayfun and cell2mat:

cellmatr = arrayfun(@(x) A(:,x) * A(:,x).', 1:size(A,2), 'uni', 0);
out = reshape(cell2mat(cellmatr), size(A,1), size(A,1), size(A,2));

我只是循环遍历1A中的所有列之间的线性索引数组,并且对于该数组中的每个元素,我都访问相应的列并计算外部乘积.因此,输出将提供一个1D的单元格网格,然后我将其转换回2D矩阵,然后将其整形为3D矩阵以查找外部乘积的3D矩阵.

I simply loop over a linear index array between 1 and as many columns we have in A, and for each element in this array, I access the corresponding column and compute the outer product. The output will thus give a 1D grid of cells, which I then convert back into a 2D matrix, then reshape into a 3D matrix to find the 3D matrix of outer products.

但是,对于大型矩阵,这是相当慢的.我还尝试在arrayfun调用中用kron(即kron(A(:,x), A(:,x)))替换矩阵乘积,但这对我来说仍然很慢.

However, for large matrices, this is quite slow. I've also tried replacing the matrix product with kron (i.e. kron(A(:,x), A(:,x))) inside my arrayfun call, but this is still quite slow for my purposes.

有人知道以这种方式计算外部产品的3D矩阵的有效方法吗?

Does anyone know of an efficient way to compute this 3D matrix of outer products in this fashion?

推荐答案

Divakar的答案相比,这只是一个小改进.因为它用2D阵列置换代替了3D阵列置换,所以速度稍快一些:

This is just a minor improvement over Divakar's answer. It is a little faster because it replaces a 3D-array permute with a 2D-array permute:

B = bsxfun(@times, permute(A, [1 3 2]), permute(A, [3 1 2]));

这篇关于有效地计算外部产品的3D矩阵-MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆