2

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

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

然后

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

谢谢!

4

1 回答 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_ind和的每个组合y_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则实际上比常规的完整矩阵消耗更多的内存。

于 2015-09-07T18:17:35.840 回答