matlab中的稀疏矩阵:将未记录的元素设置为-1而不是0

Sparse matrix in matlab: set unrecorded elements to -1 instead of 0

我想创建一个主要由 -1 组成的稀疏矩阵,但也包括一些 0 和 1。这是一个更大的项目的一部分,所以重要的是我不要将 -1 切换为 0。默认情况下, Matlab 中的 sparse(A) 仅跟踪非零元素。有没有办法只跟踪非(减去一个)元素?例如,如果

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

然后

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

谢谢!

不,无法覆盖 sparse 以使用不同的值。你可以做的是使用 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 就足够了。

一个例子:

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,因此您可以清楚地使用sparse 无论如何。在示例中,这将设置 A = [1 2;0 1],您可以使用 A-1.

调用相应的值

请注意:sparse 为每个元素(行、列、值)存储三个值,外加一些开销。因此,如果您的矩阵不到 70% 是空的,sparse 实际上比常规的完整矩阵消耗 更多 内存。