MATLAB:如何矢量矩阵相乘的两个阵列? [英] MATLAB: How to vector-multiply two arrays of matrices?

查看:456
本文介绍了MATLAB:如何矢量矩阵相乘的两个阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个3维阵列,所述第一两维其中重新present矩阵和通过parameterspace最后一个计数,作为一个简单的例子取

I have two 3-dimensional arrays, the first two dimensions of which represent matrices and the last one counts through a parameterspace, as a simple example take

A = repmat([1,2; 3,4], [1 1 4]);

(但假设 A(:,:,J)是每个 j种)。一个人怎么可以轻松地执行每 - Ĵ两个这样的矩阵阵列的矩阵乘法 A

(but assume A(:,:,j) is different for each j). How can one easily perform a per-j matrix multiplication of two such matrix-arrays A and B?

C = A; % pre-allocate, nan(size(A,1), size(B,2)) would be better but slower
for jj = 1:size(A, 3)
  C(:,:,jj) = A(:,:,jj) * B(:,:,jj);
end

肯定做工作,但如果第三维更像1E3元素,这是非常缓慢的,因为它不使用MATLAB的矢量化。那么,有没有更快的方法?

certainly does the job, but if the third dimension is more like 1e3 elements this is very slow since it doesn't use MATLAB's vectorization. So, is there a faster way?

推荐答案

我强烈建议您使用 MATLAB的MMX工具箱。它可以以最快的速度乘n维矩阵越好。

I highly recommend you use the MMX toolbox of matlab. It can multiply n-dimensional matrices as fast as possible.

的优点 MMX 是:


  1. 轻松使用。

  2. n维矩阵(实际上它可以繁殖的2-D矩阵阵列)

  3. 它执行其他的矩阵运算(转置,二次乘,澈分解等)

  4. 它使用的 C编译器多线程作为加快计算。

  1. It is easy to use.
  2. Multiply n-dimensional matrices (actually it can multiply arrays of 2-D matrices)
  3. It performs other matrix operations (transpose, Quadratic Multiply, Chol decomposition and more)
  4. It uses C compiler and multi-thread computation for speed up.

对于这个问题,您只需要编写此命令:

For this problem, you just need to write this command:

C=mmx('mul',A,B);

我增加了以下功能@ Amro的的答案

I added the following function to @Amro's answer

%# mmx toolbox
function C=func6(A,B,n,m,p)
    C=mmx('mul',A,B);
end

我得到这个结果对于 N = 2,M = 2,P = 1E5

    1.6571 # FOR-loop
    4.3110 # ARRAYFUN
    3.3731 # NUM2CELL/FOR-loop/CELL2MAT
    2.9820 # NUM2CELL/CELLFUN/CELL2MAT
    0.0244 # Loop Unrolling
    0.0221 # MMX toolbox  <===================

我用@ Amro的的code运行基准。

I used @Amro's code to run the benchmark.

这篇关于MATLAB:如何矢量矩阵相乘的两个阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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