Matlab Sparse function v.s. Python Scipy.sparse library



我正在将Matlab代码转换为Python环境,现在在Matlab中使用稀疏函数进行处理。我知道我们有一个名为scipy.sparse的图书馆,其中一个csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)]).

但是,当我检查从库中计算scipy.sparse时,它们与 Matlab 中的不匹配。 我有1693872的大数据大小,称为Ig(1693872,(,Jg(1693872,(和K_dummy(1693872,(,其中K_dummy(Ig(i),Jg(i)) = K_dummy(i)

我已经检查了所有变量,IgJgK_dummy与 Matlab 完美匹配。你们知道我必须考虑其他方面吗?

以下是我在python和Matlab中的示例代码,分别作为参考:

K = csc_matrix((K_dummy.flatten('F'),(Ig.flatten('F')-1,Jg.flatten('F')-1)),shape=(noDofs,noDofs))
K = sparse(Ig(:),Jg(:),K_dummy_python(:),noDofs,noDofs);
其中K_dummy是 (18, 18, 5228( 数组,Ig

是 (324, 5228( 数组,Jg是 (324, 5228( 数组,noDofs是一个 int 变量,如 42442。

八度:

>> data=[1,2;3,4];
>> I=[1,2,3,4];
>> J=[2,3,4,2];
>> M = sparse(I(:),J(:),data(:))
M =
Compressed Column Sparse (rows = 4, cols = 4, nnz = 4 [25%])
(1, 2) ->  1
(4, 2) ->  4
(2, 3) ->  3
(3, 4) ->  2
>> full(M)
ans =
0   1   0   0
0   0   3   0
0   0   0   2
0   4   0   0
>> save -7 sparse1.mat data I J M

numpyscipy.ioscipy.sparse

In [57]: d = loadmat('sparse1.mat')                                                              
In [58]: d                                                                                       
Out[58]: 
{'__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.2.2, 2020-01-26 19:36:04 UTC',
'__version__': '1.0',
'__globals__': [],
'data': array([[1., 2.],
[3., 4.]]),
'I': array([[1., 2., 3., 4.]]),
'J': array([[2., 3., 4., 2.]]),
'M': <4x4 sparse matrix of type '<class 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Column format>}

看看稀疏矩阵:

In [59]: d['M'].A                                                                                
Out[59]: 
array([[0., 1., 0., 0.],
[0., 0., 3., 0.],
[0., 0., 0., 2.],
[0., 4., 0., 0.]])
In [60]: print(d['M'])                                                                           
(0, 1)    1.0
(3, 1)    4.0
(1, 2)    3.0
(2, 3)    2.0

并重新创建矩阵

In [61]: M1 = sparse.csc_matrix((d['data'].flatten('F'), 
(d['I'].astype(int).flatten('F')-1, 
d['J'].astype(int).flatten('F')-1)))                                                        
In [62]: M1                                                                                      
Out[62]: 
<4x4 sparse matrix of type '<class 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Column format>
In [63]: M1.A                                                                                    
Out[63]: 
array([[0., 1., 0., 0.],
[0., 0., 3., 0.],
[0., 0., 0., 2.],
[0., 4., 0., 0.]])
In [64]: print(M1)                                                                               
(0, 1)    1.0
(3, 1)    4.0
(1, 2)    3.0
(2, 3)    2.0

使用较新的numpy/scipy我不得不将索引转换为整数(他们对浮点数作为索引变得更加挑剔(。 但是扁平化似乎工作正常。

你在所有这些变量中都有一个额外的维度,我懒得重新创建。 正确扁平化可能会导致您的问题。

最新更新