问题
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
Then
new_sparse(A) =
(1,4) = 0
(2,1) = 1
Thanks!
回答1:
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
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.
An example:
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
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
.
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.
来源:https://stackoverflow.com/questions/32444010/sparse-matrix-in-matlab-set-unrecorded-elements-to-1-instead-of-0