交换法排序matlab,matlab – 通过交换行和列重新排列稀疏数组

CSC格式保留所有非零条目的行索引列表,CSR格式保留所有非零条目的列索引列表.我认为你可以利用这个来交换周围的东西,我认为不应该有任何副作用:

def swap_rows(mat, a, b) :

mat_csc = scipy.sparse.csc_matrix(mat)

a_idx = np.where(mat_csc.indices == a)

b_idx = np.where(mat_csc.indices == b)

mat_csc.indices[a_idx] = b

mat_csc.indices[b_idx] = a

return mat_csc.asformat(mat.format)

def swap_cols(mat, a, b) :

mat_csr = scipy.sparse.csr_matrix(mat)

a_idx = np.where(mat_csr.indices == a)

b_idx = np.where(mat_csr.indices == b)

mat_csr.indices[a_idx] = b

mat_csr.indices[b_idx] = a

return mat_csr.asformat(mat.format)

你现在可以这样做:

>>> mat = np.zeros((5,5))

>>> mat[[1, 2, 3, 3], [0, 2, 2, 4]] = 1

>>> mat = scipy.sparse.lil_matrix(mat)

>>> mat.todense()

matrix([[ 0., 0., 0., 0., 0.],

[ 1., 0., 0., 0., 0.],

[ 0., 0., 1., 0., 0.],

[ 0., 0., 1., 0., 1.],

[ 0., 0., 0., 0., 0.]])

>>> swap_rows(mat, 1, 3)

<5x5 sparse matrix of type ''

with 4 stored elements in LInked List format>

>>> swap_rows(mat, 1, 3).todense()

matrix([[ 0., 0., 0., 0., 0.],

[ 0., 0., 1., 0., 1.],

[ 0., 0., 1., 0., 0.],

[ 1., 0., 0., 0., 0.],

[ 0., 0., 0., 0., 0.]])

>>> swap_cols(mat, 0, 4)

<5x5 sparse matrix of type ''

with 4 stored elements in LInked List format>

>>> swap_cols(mat, 0, 4).todense()

matrix([[ 0., 0., 0., 0., 0.],

[ 0., 0., 0., 0., 1.],

[ 0., 0., 1., 0., 0.],

[ 1., 0., 1., 0., 0.],

[ 0., 0., 0., 0., 0.]])

我使用了LIL矩阵来展示如何保留输出的类型.在您的应用程序中,您可能希望已经采用CSC或CSR格式,并根据它选择是先交换行还是列,以最大限度地减少转换.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值