Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance MATLAB中外积乘以标量的和_Performance_Matlab_Vectorization_Product_Outer Join - Fatal编程技术网

Performance MATLAB中外积乘以标量的和

Performance MATLAB中外积乘以标量的和,performance,matlab,vectorization,product,outer-join,Performance,Matlab,Vectorization,Product,Outer Join,我想在下文中对乘积和进行矢量化,以加快我的Matlab代码的速度。可能吗 for i=1:N A=A+hazard(i)*Z(i,:)'*Z(i,:); end 其中,hazard是一个向量(nx1),Z是一个矩阵(nxp) 谢谢 您可以使用和矩阵乘法- A = bsxfun(@times,Z,hazard).'*Z + A 仅使用矩阵乘法: A = A + Z'*diag(hazard)*Z; 但是,请注意,这需要更多的操作,因为diag(hazard)是一个NxN矩阵,主要由

我想在下文中对乘积和进行矢量化,以加快我的Matlab代码的速度。可能吗

for i=1:N
    A=A+hazard(i)*Z(i,:)'*Z(i,:);
end
其中,
hazard
是一个向量(nx1),
Z
是一个矩阵(nxp)

谢谢

您可以使用和
矩阵乘法
-

A =  bsxfun(@times,Z,hazard).'*Z + A

仅使用矩阵乘法:

A = A + Z'*diag(hazard)*Z;
但是,请注意,这需要更多的操作,因为
diag(hazard)
是一个
N
x
N
矩阵,主要由零组成

为了节省时间,您可以使用将内部矩阵定义为
sparse
,以便优化乘法:

A = A + full(Z'*spdiags(hazard, 0, zeros(N))*Z);
标杆管理 定时代码:

Z = rand(N,p);
hazard = rand(N,1);
timeit(@() Z'*diag(hazard)*Z)
timeit(@() full(Z'*spdiags(hazard, 0, zeros(N))*Z))
timeit(@() bsxfun(@times,Z,hazard)'*Z)
N=1000;p=300

ans =
    0.1423
ans =
    0.0441
ans =
    0.0325
ans =
    1.8889
ans =
    0.7110
ans =
    0.6600
ans =
    1.8159
ans =
    1.2471
ans =
    1.2264
N=2000;p=1000

ans =
    0.1423
ans =
    0.0441
ans =
    0.0325
ans =
    1.8889
ans =
    0.7110
ans =
    0.6600
ans =
    1.8159
ans =
    1.2471
ans =
    1.2264
N=1000;p=2000

ans =
    0.1423
ans =
    0.0441
ans =
    0.0325
ans =
    1.8889
ans =
    0.7110
ans =
    0.6600
ans =
    1.8159
ans =
    1.2471
ans =
    1.2264

可以看出,基于
bsxfun
的方法始终更快。

非常感谢!但是,如果不使用bsxfun(仅使用向量/矩阵的乘积),它就无法将其矢量化。AlessandroBeretta您可以使用repmat:
repmat(hazard,1,p)。*Z
,但是
bsxfun
有什么不情愿的?不,这只是因为计算时间似乎没有减少太多。。。。无论如何,再次感谢你的回答!我添加了一些基准测试。基于
bsxfun
的方法在我测试过的所有情况下都更快!添加
A
maybe?@divakaroops!谢谢纠正了,甚至更好!我试着使用tic/toc,你的方法快了20%!我很高兴这对你来说很快。但对于可靠的时间,你应该使用。基于
bsxfun
的方法在我的计算机上似乎要快得多。请看我的计时(我已经编辑了我的答案)纯矩阵乘法版本的意图马上就很清楚了,这弥补了IMO的微小速度差异。