如何在不使用for循环的情况下在matlab中计算二元? [英] How can I calculate dyadics in matlab without using for loops?

查看:95
本文介绍了如何在不使用for循环的情况下在matlab中计算二元?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以帮助我解决我的问题.

I was wondering if someone could help me with my problem.

让我们说我在维度[M,N,3]的张量r中具有MxN个向量的坐标.我想将所有二元乘积r_0'* r_0保存在3M×3N的块矩阵中,其中r_0是向量r_0 = r(m,n,:)对于m和n,我想这样做不使用for循环.

Let say that I have the coordinates of MxN vectors in a tensor r of dimensions [M,N,3]. I would like to save in a 3M-by-3N block matrix all dyadic products r_0'*r_0, where r_0 is the vector r_0 = r(m,n,:) for some m and n, and I would like to do this without using for loops.

如果没有正确解释自己,这是一个示例代码,显示了我想要获得的内容(当然,使用for循环):

If haven't explain myself correctly, here is an example code that shows what I would like to obtain (but using for loops, of course):

N=10;
M=5;
r=rand(M,N,3);
Dyadic=zeros(3*M,3*N);
for m=1:M
    a1=3*m-2;
    a2=3*m;
    for n=1:N
        b1=3*n-2;
        b2=3*n;
        aux(3)=r(m,n,3);
        aux(2)=r(m,n,2);
        aux(1)=r(m,n,1);
        Dyadic(a1:a2,b1:b2)=transpose(aux)*aux
    end
end

提前谢谢!

推荐答案

您需要使用bsxfun(@times,然后重新排列元素以具有所需的输出-

You need to use bsxfun(@times and then re-arrange elements to have the desired output -

%// Get the multipliication result
mat_mult = bsxfun(@times,permute(r,[1 2 4 3]),r);
 %// OR if you would like to keep mat_mult as 3D that could be potentially faster -
 %//     mat_mult = bsxfun(@times,reshape(r,[],3),permute(reshape(r,[],3),[1 3 2]));

%// Re-arrange elements to have them the way you are indexing in nested loops
Dyadic = reshape(permute(reshape(mat_mult,M,N,3,[]),[3 1 4 2]),M*3,N*3);

此解决方案的主要作用实际上是在获得乘法结果之后重新排列元素.

The major play about this solution is really the re-arrangement of elements after we have the multiplication result.

快速运行时测试,其中输入r作为1000 x 1000 x 3大小的数组,表明这种基于bsxfun的方法在嵌套上提供了 20x 的加速问题中列出的循环代码!

Quick runtime tests with the input r as 1000 x 1000 x 3 sized array, show that this bsxfun based approach gives over 20x speedup over the nested loop code listed in the question!

这篇关于如何在不使用for循环的情况下在matlab中计算二元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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