矩阵乘法中的 bsxfun 实现 [英] bsxfun implementation in matrix multiplication
问题描述
一如既往地向您学习更多信息,我希望我能在以下代码方面得到一些帮助.
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
值与 A
的 every
值相乘,这意味着:
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]
这将给我这个 new_matrix
大小为 (12*m x n)
假设 A (mxn)
.在这种情况下 (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
发送到三维,这样在使用 bsxfun
时,单例扩展就会生效对于与 A
的乘法,将乘积结果扩展到第三维.然后,执行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屋!