matlab - 将一个向量的每个元素乘以另一个向量的每个元素

标签 matlab vector vectorization multiplication elementwise-operations

我有两个非常大的列向量,AB , 大小 ax1bx1 , 分别。我想构造一个向量 C尺寸(b*a)x1通过计算 A(i)*B(j)对于每个 ij .为了说明我的意思:

clear
a=10^3;
b=10^3;
A=randn(a,1);
B=randn(b,1);
Ctemp=zeros(a,b);
for i=1:a
    for j=1:b
        Ctemp(i,j)=A(i)*B(j);
    end
end
C=reshape(Ctemp, a*b,1);

问题:有没有更高效的方式获取C哪个避免双重循环?我的实际ab大于10^3 .

最佳答案

这是一个可以从隐式(或显式)扩展中获益的简单数组乘法示例:

% Implicit (R2016b and newer):
C = A(:) .* B(:).'; % optionally surround by reshape( ... , [], 1);

% "Explicit" (R2007a and newer):
C = bsxfun( @times, A(:), B(:).' );

从那里开始,这只是 reshape 的问题,正如您已经在做的那样(D = C(:)D = C(:).')。

关于matlab - 将一个向量的每个元素乘以另一个向量的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52689323/

相关文章:

r - 如何将 Curry() 与 Vectorize() 结合起来?

python - NumPy:向量化到一组点的距离总和

python - NumPy 版本的 "Exponential weighted moving average",相当于 pandas.ewm().mean()

matlab - 如何将 PixelList 转换为 mask ?

c++ - 在 vector 中编写线程安全

python - 计算相似向量的频率

c++ - 更改已推送的列表(在 vector 上)是否会更改 vector 上的列表?

Matlab:二维离散傅里叶变换和逆变换

matlab - 从自身内部删除 MATLAB 脚本是否安全?

MATLAB调试: smarter way to stop the code with an specific condition?