MATLAB:无循环的块矩阵乘法 [英] MATLAB: Block matrix multiplying without loops

查看:100
本文介绍了MATLAB:无循环的块矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个块矩阵[A B C...]和一个矩阵 D (均为二维). D 的尺寸为y-y,而 A,B,C 等的尺寸均为z-y.基本上,我要计算的是矩阵[D*(A'); D*(B'); D*(C');...],其中 X '是指 X 的转置.但是,出于速度考虑,我想在不使用循环的情况下完成此操作.

I have a block matrix [A B C...] and a matrix D (all 2-dimensional). D has dimensions y-by-y, and A, B, C, etc are each z-by-y. Basically, what I want to compute is the matrix [D*(A'); D*(B'); D*(C');...], where X' refers to the transpose of X. However, I want to accomplish this without loops for speed considerations.

我已经使用了reshape命令好几个小时了,我知道在其他情况下如何使用它,但是这个用例不同于其他用例,因此我无法弄清楚.我还要尽可能避免使用多维矩阵.

I have been playing with the reshape command for several hours now, and I know how to use it in other cases, but this use case is different from the other ones and I cannot figure it out. I also would like to avoid using multi-dimensional matrices if at all possible.

推荐答案

老实说,循环可能是最好的方法.在我的图像处理工作中,我发现一个写得很好的循环利用Matlab的JIT编译器通常比处理数据以使用矢量化操作的所有额外开销更快.这样的循环:

Honestly, a loop is probably the best way to do it. In my image-processing work I found a well-written loop that takes advantage of Matlab's JIT compiler is often faster than all the extra overhead of manipulating the data to be able to use a vectorised operation. A loop like this:

[m n] = size(A);
T = zeros(m, n);
AT = A';
for ii=1:m:n
    T(:, ii:ii+m-1) = D * AT(ii:ii+m-1, :);
end

仅包含内置运算符,几乎没有复制,并且鉴于JIT很难被击败.即使您想考虑解释器的开销,它仍然只是一个没有考虑功能的语句.

contains only built-in operators and the bare minimum of copying, and given the JIT is going to be hard to beat. Even if you want to factor in interpreter overhead it's still only a single statement with no functions to consider.

具有更多功能和内存复制功能的无循环"版本为 a隐藏循环:

The "loop-free" version with extra faffing around and memory copying, is to split the matrix and iterate over the blocks with a hidden loop:

blksize = size(D, 1);
blkcnt = size(A, 2) / blksize;
blocks = mat2cell(A, blksize, repmat(blksize,1,blkcnt));
blocks = cellfun(@(x) D*x', blocks, 'UniformOutput', false);
T = cell2mat(blocks);

当然,如果您有权使用图像处理工具箱,则也可以

Of course, if you have access to the Image Processing Toolbox, you can also cheat horribly:

T = blockproc(A, size(D), @(x) D*x.data');

这篇关于MATLAB:无循环的块矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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