bsxfun在矩阵乘法中的实现 [英] bsxfun implementation in matrix multiplication

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

问题描述

一如既往地向您学习更多,我希望我可以从以下代码中获得一些帮助.

As always trying to learn more from you, I was hoping I could receive some help with the following code.

我需要完成以下任务:

1)我有一个向量:

x = [1 2 3 4 5 6 7 8 9 10 11 12]

2)和一个矩阵:

A =[11    14    1
    5     8    18
    10    8    19
    13    20   16]

我需要能够将x中的each值与Aevery值相乘,这意味着:

I need to be able to multiply each value from x with every value of A, this means:

new_matrix = [1* A
              2* A
              3* A
               ...
              12* A]

假设A (mxn),这将给我这个(12*m x n)大小的(12*m x n).在这种情况下(12*4x3)

This will give me this new_matrix of size (12*m x n) assuming A (mxn). And in this case (12*4x3)

如何使用matlab中的bsxfun来执行此操作?而且,这种方法会比for-loop更快吗?

How can I do this using bsxfun from matlab? and, would this method be faster than a for-loop?

关于我的for-loop,我在这里也需要一些帮助...当循环运行时,我无法存储每个"new_matrix":(

Regarding my for-loop, I need some help here as well... I am not able to storage each "new_matrix" as the loop runs :(

for i=x
new_matrix = A.*x(i)
end

提前谢谢!!

在给出解决方案之后

第一个解决方案

clear all
clc
x=1:0.1:50;
A = rand(1000,1000);
tic
val = bsxfun(@times,A,permute(x,[3 1 2]));
out = reshape(permute(val,[1 3 2]),size(val,1)*size(val,3),[]);
toc

输出:

Elapsed time is 7.597939 seconds.

第二个解决方案

clear all
clc
x=1:0.1:50;
A = rand(1000,1000);
tic
Ps = kron(x.',A);
toc

输出:

Elapsed time is 48.445417 seconds.

推荐答案

x发送到第三维,这样,当bsxfunA乘法使用时,单例扩展将生效,从而扩展了乘积结果到第三维.然后,执行bsxfun乘法-

Send x to the third dimension, so that singleton expansion would come into effect when bsxfun is used for multiplication with A, extending the product result to the third dimension. Then, perform the bsxfun multiplication -

val = bsxfun(@times,A,permute(x,[3 1 2])) 

现在,val是一个3D矩阵,并且期望的输出将是一个沿着第三个维度沿列连接的2D矩阵.这是在下面实现的-

Now, val is a 3D matrix and the desired output is expected to be a 2D matrix concatenated along the columns through the third dimension. This is achieved below -

out = reshape(permute(val,[1 3 2]),size(val,1)*size(val,3),[])

希望是有道理的!传播bsxfun一词!呜! :)

Hope that made sense! Spread the bsxfun word around! woo!! :)

这篇关于bsxfun在矩阵乘法中的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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