Matlab: Why is full/sparse matrix addition slower than full/full matrix addition?

五迷三道 提交于 2019-12-11 05:45:00

问题


Why is adding a sparse and a full matrix slower than adding two full matrices? The following code demonstrates consistent superior performance for hFullAddFull.

I_FULL = 600;
J_FULL = 10000;
FULL_COUNT = I_FULL*J_FULL;
NON_ZERO_ELEMENT_COUNT = 1000;

nonZeroIdxs = randsample(FULL_COUNT, NON_ZERO_ELEMENT_COUNT);
mat_Sp = spalloc(I_FULL, J_FULL, NON_ZERO_ELEMENT_COUNT);
mat_Sp(nonZeroIdxs) = 0.5;
mat_Full = full(mat_Sp);

otherMat_Full = rand(I_FULL, J_FULL);

hFullAddSp = @()otherMat_Full+mat_Sp;
hFullAddFull = @()otherMat_Full+mat_Full;

timeit(hFullAddSp)
timeit(hFullAddFull)

For me this is important as the addition occurs within a critical piece of code that is called 10,000s of times, so the small performance decrease for the sparse addition is critical. I would rather keep my code with the sparse type as input to the calculation and having the final matrix as a full matrix. Surely the 1000 elements of the full matrix can simply be modified? What is going on underneath here? Is there a way to make the sparse/full addition faster? Would a mex implementation be faster?

On my machine hFullAddFull is 30% faster.

来源:https://stackoverflow.com/questions/49931838/matlab-why-is-full-sparse-matrix-addition-slower-than-full-full-matrix-addition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!