Matlab索引稀疏矩阵 [英] Matlab Indexing Sparse Matrix

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

问题描述

让我们说这3个向量定义了以下稀疏矩阵:

Let's say we have the following sparse matrix defined by this 3 vectors:

[lines, columns, values] = find(A)

lines =

     1
     2
     3
     5
     1
     3
     3
     5
     4
     5


columns =

     1
     2
     2
     2
     3
     3
     4
     4
     5
     5


values =

     3
     4
     7
     3
     1
     5
     9
     6
     2
     5

我要实现的目标是访问(2,2)位置的元素

What I am trying to achieve is to access the element at the position (2, 2)

我知道您可以执行values(lines == 2)(values(columns == 2)),它将返回第二行(列)中的所有值.

I know you can do values(lines == 2) (values(columns == 2)) which will return all the values from second row (column).

我的问题是,如何执行values(lines == 2 && columns == 2)之类的操作来获取A(2,2)处的值?

My question is how can you do something like values(lines == 2 && columns == 2) to get the value at A(2,2)?

推荐答案

如果您要访问稀疏矩阵或与此相关的任何其他矩阵中的元素.这没有任何开销.如果有人能证明我做错了,我非常希望看到它的基准,因为那样的话,我就错过了非常重要的事情!

If you want to access elements in a sparse matrix, or any other matrix for that matter. This has no overhead whatsoever. If anyone can prove me wrong on this one, I would very much like to see a benchmark of it, because then I have missed something very important!

a = Q(2,2);

如果您要添加元素到稀疏矩阵中,这也非常简单.我也不认为有任何更快方法来做到这一点.同样,如果有人可以证明我错了,请分享您的基准测试结果!

If you want to add elements to a sparse matrix, this is also very simple. I don't think there are any faster ways to do this either. Again, if anyone can prove me wrong, please share your benchmark results!

如果您有:

lines = [ 1
     2
     3
     5
     1];


columns = [1
     2
     2
     2
     3];


values = [3
     4
     7
     3
     1];
 
 Q = sparse(lines, columns, values)
  (1, 1) ->  3
  (2, 2) ->  4
  (3, 2) ->  7
  (5, 2) ->  3
  (1, 3) ->  1

 [linesF, columnsF, valuesF] = find(Q)
 
 %% Now add the value 12 to position (3,1)
 linesF = [linesF; 3];
 columnsF = [columnsF; 1];
 valuesF = [valuesF; 12];
 
 Q = sparse(linesF, columnsF, valuesF)
 
  (1, 1) ->  3
  (3, 1) ->  12
  (2, 2) ->  4
  (3, 2) ->  7
  (5, 2) ->  3
  (1, 3) ->  1

之所以行之有效,是因为没有人说必须对行向量和列向量进行任何排序.

This works because there is nothing saying the row and column vectors must be sorted in any way.

S = sprand(10000,10000,0.0005);
tic
for ii = 1:1000
    var = S(r,c);
end
toc
Elapsed time is 0.010705 seconds.

[i,j,s] = find(S);
tic
for ii = 1:1000
    var = s((i == r & j == c);  % (r,c) is a random non-zero element in s
end
toc
Elapsed time is 0.296547 seconds.

这篇关于Matlab索引稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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