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

问题描述

我试图逐个元素地将小矩阵(比如2x2)中的每个元素与大矩阵(比如4x4)中的每个位置相乘.

I'm trying to multiply every element in a small matrix (let's say 2x2) with every position in a big matrix (let's say 4x4), element by element.

所以我想要

        1 2 3 4     1 0 3 0
1 0     1 2 3 4     0 0 0 0
0 0 'x' 1 2 3 4  =  1 0 3 0
        1 2 3 4     0 0 0 0

小矩阵会根据需要多次应用,并且乘法逐个元素地进行.我已经尝试了很多循环,但是在MATLAB中感觉不对,必须有更漂亮的方法吗?

The small matrix is applied as many times as it fits, and the multiplication is element by element. I've tried a bunch of loops, but that doesn't feel right in MATLAB, there must be prettier ways of doing it?

推荐答案

一种可能性是使用repmat尽可能多次重复小的矩阵:

One possibility is to use repmat to repeat the small matrix as many times as necessary:

C = repmat(A,size(B,1)/size(A,1),size(B,2)/size(A,2)).*B


另一种避免使用repmat的可能性:切开大矩阵,将块排列在第三维和第四维中,然后使用bsxfun进行乘法:


Another possibility, which avoids repmat: cut up the large matrix, arrange the pieces in the third and fourth dimensions, and use bsxfun to do the multiplication:

[m n] = size(A);
[M N] = size(B);
T = permute(reshape(B,M,n,[]), [2 1 3]);
T = permute(reshape(T,n,m,[],size(T,3)),[2 1 3 4]);
C = cell2mat(squeeze(mat2cell(bsxfun(@times,T,A),m,n,ones(1,M/m),ones(1,N/n))));

(这两行T = ...进行了剪切,这是由于.)

(The two lines T = ... do the cutting, and are due to A. Donda.)

这种方法的优势在于,如果内存问题很大,您可以覆盖B而不是定义T,从而节省了内存:

The advantage of this approach is that, if memory is an issue, you can overwrite B instead of defining T, thus saving memory:

[m n] = size(A);
[M N] = size(B);
B = permute(reshape(B,M,n,[]),[2 1 3]);
B = permute(reshape(B,n,m,[],size(B,3)),[2 1 3 4]);
C = cell2mat(squeeze(mat2cell(bsxfun(@times,B,A),m,n,ones(1,M/m),ones(1,N/n))));

这篇关于将小矩阵乘以大矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:14