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

查看:35
本文介绍了有效计算外积的 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 矩阵,使得该输出矩阵的第 ith 个切片是第 ith 列的外积A 与自身.两个向量 uv 之间的外积就是 u*v.' 如果 uv 都是列向量.

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.

然而,对于大型矩阵,这很慢.我也试过用 kron(即 kron(A(:,x), A(:,x))) 替换我的 arrayfun 中的矩阵乘积 调用,但这对我来说仍然很慢.

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天全站免登陆