Matlab中的稀疏矩阵:将未记录的元素设置为-1而不是0 [英] Sparse matrix in matlab: set unrecorded elements to -1 instead of 0

查看:116
本文介绍了Matlab中的稀疏矩阵:将未记录的元素设置为-1而不是0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个主要由-1组成的稀疏矩阵,但也包含一些0和1.这是一个较大项目的一部分,因此,请勿将-1切换为0非常重要.默认情况下,稀疏Matlab中的(A)仅跟踪非零元素.有没有办法只跟踪非(负一个)元素?例如,如果

I want to create a sparse matrix consisting mainly of -1, but also includes some 0 and 1. This is part of a larger project, so it is important that I do not switch -1 with 0. As default, sparse(A) in Matlab keeps track of only non-zero elements. Is there a way to keep track of only non-(minus one) elements? For example, if

A = 
-1 -1 -1  0 
 1 -1 -1 -1

然后

new_sparse(A) =
(1,4) = 0
(2,1) = 1

谢谢!

推荐答案

否,没有方法可以覆盖sparse以使用不同的值.尽管浪费时间和内存,但您可以做的是使用accumarray:

No, there is no way to override sparse to use different values. What you can do, though time and memory consuming, is to use accumarray:

x_ind; % I presume this to contain the column index of the number
y_ind; % I presume this to contain the row  index of the number
value; % I presume this to contain the value (0 or 1)
new_mat = accumarray([x_ind y_ind],value,[],[],-1);

new_mat现在将包含您指定的01值,并且在所有其他位置上具有-1.您不必设置size参数(第三个参数),因为如果放置[],它只会创建max(x_ind) x max(y_ind)大小的矩阵.第四个输入参数(函数)也可以为空,因为x_indy_ind的每个组合将只包含一个值,因此默认值mean就足够了.

new_mat now will contain your prescribed 0 and 1 values, and has -1 on all other locations. You do not have to set the size argument (the third) since it will just create a matrix of max(x_ind) x max(y_ind) size if you put []. The fourth input argument, the function, can be empty as well, since each combination of x_ind and y_ind will contain only one value, thus the default, mean is sufficient.

一个例子:

A = [0 1 ; -1 0];
x_ind = [1;2;2];
y_ind = [1;1;2];
value = [0;1;0];
new_mat = accumarray([x_ind y_ind],value,[],[],-1);

new_mat = 
          0    1
          -1   0

我更喜欢的另一种方法是将一个简单地添加到所有值,从而使您的值为1 2并将0设置为1.这种方式-1被映射为0,因此您显然可以使用无论如何.在示例中,这将设置A = [1 2;0 1],您可以使用A-1调用各自的值.

A different method which I'd prefer is to simply add one to all values, thus making your 1 2 and setting your 0 to 1. This way -1 is mapped to 0 and therefore you're clear to use sparse anyway. In the example this would set A = [1 2;0 1] which you can call with your respective values using A-1.

请注意:sparse为每个元素(行,列,值)存储三个值,以及一些开销.因此,如果您的矩阵中的空白少于大约70%,则sparse实际上比常规的完整矩阵消耗的更多内存.

Just as a note: sparse stores three values for each element (row, column, value), plus some overhead. So if your matrix is less than about 70% empty, sparse is actually consuming more memory than a regular, full matrix.

这篇关于Matlab中的稀疏矩阵:将未记录的元素设置为-1而不是0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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