MATLAB:如何向量乘以两个矩阵数组? [英] MATLAB: How to vector-multiply two arrays of matrices?

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

问题描述

我有两个3维数组,前两个维度代表矩阵,最后一个通过参数空间计数,举个简单的例子

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 都是不同的).如何轻松地执行两个这样的矩阵数组 AB 的 per-j 矩阵乘法?

(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?

推荐答案

我强烈建议您使用 MMX 工具箱 的 matlab.它可以尽可能快地乘以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维矩阵(实际上它可以乘以二维矩阵数组)
  3. 它执行其他矩阵运算(转置、二次乘法、Chol 分解等)
  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 的代码来运行基准测试.

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

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

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