是否可以在 Julia 中重塑稀疏数组?

Is it possible to reshape a sparse array in Julia?

我试图在 Julia 中重塑稀疏数组,但在这样做时出现错误。有可能吗?如果是,怎么做?

一些沮丧的快照:

julia> A = sparse([1, 2, 3], [1, 2, 3], [1, 2, 3])
3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
  [1, 1]  =  1
  [2, 2]  =  2
  [3, 3]  =  3

julia> reshape(A, (5, 5))
ERROR: DimensionMismatch("parent has 9 elements, which is incompatible with size (5, 5)")
Stacktrace:
julia> A.m
3

julia> A.m = 4
ERROR: setfield! immutable struct of type SparseMatrixCSC cannot be changed
Stacktrace:
julia> J = Base.ReshapedArray(A, (4, 4), ())
4×4 reshape(::SparseMatrixCSC{Int64,Int64}, 4, 4) with eltype Int64:
 1  2    3     #undef
 0  0  #undef  #undef
 0  0  #undef  #undef
 0  0  #undef  #undef

julia> J[4, 4] = 4
ERROR: BoundsError: attempt to access 3×3 SparseMatrixCSC{Int64,Int64} at index [1, 6]
Stacktrace:

我也尝试了 resize!(A, 4*4),但似乎没有任何效果。同样,我们将不胜感激任何帮助。

编辑:我应该更清楚,我想专门调整数组的大小以添加 3x3 范围之外的更多元素(在示例代码中)。点赞 A[4, 4] = 1 目前不可用。

您可以使用

创建一个新的稀疏数组
julia> i, j, v = findnz(A)
([1, 2, 3], [1, 2, 3], [1, 2, 3])

julia> sparse(i, j, v, 5, 5)
5×5 SparseMatrixCSC{Int64, Int64} with 3 stored entries:
 1  ⋅  ⋅  ⋅  ⋅
 ⋅  2  ⋅  ⋅  ⋅
 ⋅  ⋅  3  ⋅  ⋅
 ⋅  ⋅  ⋅  ⋅  ⋅
 ⋅  ⋅  ⋅  ⋅  ⋅

sparse 的逆运算是 findnz,它检索用于创建稀疏数组的输入。见 docs.

(编辑,请注意我的输出与您的不同,因为我使用了 Julia v1.6(在撰写本文时为候选版本 1 或 rc1),它有这个很酷的新功能 show 稀疏矩阵的方法。)