今天的Guest Blogger是Mary Fenelon,他是MathWorks优化和数学的产品营销经理。在今天的帖子中,她描述了如何使用新的名词矩阵函数可以简化您的代码并提高性能。
For example, if A and B are 3-D arrays and you want to compute the array C to be the collection of matrices formed by multiplying the matrices contained in the first two dimensions of A and B, you could do this with the statement
C = pagemtimes(A,B).
除了循环之外的替代方案
pagemtimes
are
dlmti
对于
dlarray.
在深度学习工具箱和
Pagefun.
对于
gpuArray
并在并行计算工具箱中分布式阵列。这些仍然可用,但现在您可以使用pagemtips进行常规阵列以及
dlarray.
and
gpuArray
。
有时您只需要转换矩阵集合。现在你可以使用
pagetranspose
代替
permute
。
Easier
In this example, the matrices to be multiplied are stored in the first two dimensions of a 4-D array
这款双嵌套For-Loop计算了矩阵矩阵产品。s manbetx 845
C1 =零(尺寸(a,1),尺寸(b,1),6,7);
C1(:,:,p,q) = A(:,:,p,q)*B(:,:,p,q).';
使用
pagemtimes
那that code can be simplified to a single function call:
C2 = pagemtimes(A,'没有'B,B,'transpose');
这肯定更容易。字符串选项指定应在乘法中使用页面 - WIDE rance otherθ。
pagemtimes
implicitly expands the dimensions beyond three to multiply all combinations of the paged matrices.
Faster
现在我已经让这种情况更轻松,如何更快?加速是否随着N-D阵列的大小而变化?下面的循环通过一组矩阵,其具有不同行大小的第一矩阵,但否则固定尺寸。我绘制了时代和加速。
CLoop = loopmtimes(A,B,m,k,p);
f = @()loopmtimes(A,B,m,k,p);
plotTimes(mset,n,p,k,tPage,tLoop);
The Times plot shows that the for-loop takes more time than
pagemtimes
。速度升起的情节表明使用的好处
pagemtimes
is largest when there are many small matrices but even for the larger values of
m
那the speed-up is still substantial. The improvement for smaller matrices is more significant because the overhead that is being eliminated makes up a larger percentage of the overall time.
我喜欢使用
timeit
代替
Tic.
/
TOC.
对于时间(见
以前的帖子
on
timeit
)即使它需要将代码放入函数时。
timeit
运行代码多次并采取中值测量。这是推荐的方法
衡量代码的性能
。即便如此,使用代码需要一个非常少量的时间运行,例如矩阵大小很小,
timeit
将无法恢复准确的时间。在这种情况下的建议是在循环中多次运行代码。
如果您尝试使用A和B的尺寸的不同值,您将看到不同的加速。例如,当数组很大并且只有几页时,由于大多数工作都处于实际矩阵乘法中,因此不会太大。由于小矩阵的难度以及大矩阵的高速缓存和螺纹的影响,您也可能看到一些不规则性。
More
可以为其他矩阵函数编写分页功能。我们应该先做哪些,并且在他们将使用哪些应用程序?让我们知道
here
。
Helper Functions
functionCloop = loopmtimes(A,B,m,k,p)
functionplotTimes(mset,n,p,k,tPage,tLoop)
数字('Position',[100,100,1200,450])
传说({'pagemtimes'那'for-loop'},'Location'那'northwest');
title(“循环的Pagemtimes的加速”)
titleStr = sprintf('Multiply A (m-by-%d-by-%d) by B (%d-by-%d)',n,p,n,k);
Copyright 2021 The MathWorks, Inc.
Comments
To leave a comment, please clickhereto sign in to your MathWorks Account or create a new one.