在Matlab中向稀疏向量添加稀疏向量 [英] Adding a sparse vector to a dense vector in Matlab

查看:331
本文介绍了在Matlab中向稀疏向量添加稀疏向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个高维向量v,它很密集,而另一个高维向量x是稀疏的,我想做一个看起来像

Suppose I have a high dimensional vector v which is dense and another high dimensional vector x which is sparse and I want to do an operation which looks like

v = v + x

v = v + x

理想情况下,由于只需要更新v中的几个条目,此操作应该很快,但是即使我声明x为稀疏状态,它仍然要花费大量时间.我已经尝试过v处于完全状态以及v处于稀疏状态,并且两者都相当慢.

Ideally since one needs to update only a few entries in v this operation should be fast but it is still taking a good amount of time even when I have declared x to be sparse. I have tried with v being in full as well as v being in sparse form and both are fairly slow.

我还试图通过调用find从稀疏向量x中提取索引,然后在for循环中更新原始向量.这比上面的操作要快,但是有一种方法可以用更少的代码来实现相同的目的.

I have also tried to extract the indices from the sparse vector x by calling a find and then updating the original vector in a for loop. This is faster than the above operations, but is there a way to achieve the same with much less code.

谢谢

推荐答案

如果两个操作数都稀疏,则二进制运算符将产生稀疏结果;如果两个操作数都充满,则将产生完整结果.对于混合操作数,除非操作保留稀疏性,否则结果将是完整的. 如果S稀疏且F充满,则S + F,S * F和F \ S充满,而S. * F和S& F稀疏.即使矩阵几乎没有零元素,也可能是稀疏的.

Binary operators yield sparse results if both operands are sparse, and full results if both are full. For mixed operands, the result is full unless the operation preserves sparsity. If S is sparse and F is full, then S+F, S*F, and F\S are full, while S.*F and S&F are sparse. In some cases, the result might be sparse even though the matrix has few zero elements.

因此,如果您希望保持x稀疏,我认为最好使用逻辑索引以x的非零值更新v.以下是一个示例函数,该函数显示逻辑索引编制或显式full -ing x最佳(至少在我的R2015a安装上):

Therefore, if you wish to keep x sparse, I think using logical indexing to update v with the nonzero values of x is best. Here is a sample function that shows either logical indexing or explicitly full-ing x is best (at least on my R2015a install):

function [] = blur()

    n = 5E6;
    v = rand(n,1);
    x = sprand(n,1,0.001);
    xf = full(x);
    vs = sparse(v);

    disp(['Full-Sparse:   ',num2str(timeit(@() v + x)      ,'%9.5f')]);
    disp(['Full-Full:     ',num2str(timeit(@() v + xf)     ,'%9.5f')]);
    disp(['Sparse-Sparse: ',num2str(timeit(@() vs + x)     ,'%9.5f')]);
    disp(['Logical Index: ',num2str(timeit(@() update(v,x)),'%9.5f')]);

end

function [] = update(v,x)

    mask = x ~= 0;
    v(mask) = v(mask) + x(mask);

end

这篇关于在Matlab中向稀疏向量添加稀疏向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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