将Matlab的sparse()代码转换为numpy/scipy的csc_matrix()时的问题
我对Matlab和Python都还是个新手,所以如果这个问题有点傻,请多多包涵...
我正在尝试把一些Matlab代码转换成Python,使用numpy和scipy,一开始一切都很顺利,直到我遇到了一个稀疏矩阵,这是别人写的。Matlab代码是这样的:
unwarpMatrix = sparse(phaseOrigin, ceil([1:nRead*nSlice*nPhaseDmap]/expan), 1, numPoints, numPoints)/expan;
这是我在尝试转换之前写的Python代码(包含我的思路)。我在测试一个数据集(在Matlab和Python中都用的是这个数据集):
nread = 64
nslice = 28
nphasedmap = 3200
expan = 100
numpoints = 57344
所以,phaseorigin、s和j数组的长度都是5734400(我确认生成phaseorigin数组的函数输出和Matlab完全一样)
#Matlab sparse takes: S = sparse(i,j,s,m,n)
#Generates an m by n sparse matrix such that: S(i(k),j(k)) = s(k)
#scipy csc matrix takes: csc_matrix((data, ij), shape=(M, N))
#Matlab code is: unwarpMatrix = sparse(phaseOrigin, ceil([1:nRead*nSlice*nPhaseDmap]/expan), 1, numPoints, numPoints)/expan;
size = nread*nslice*nphasedmap
#i would be phaseOrigin variable
j = np.ceil(np.arange(1,size+1, dtype=np.double)/expan)
#Matlab apparently treats '1' as a scalar so I should be tiling 1 to the same size as j and phaseorigin
s = np.tile(1,size)
unwarpmatrix = csc_matrix((s,(phaseorigin, j)), shape=(numpoints,numpoints))/expan
但是当我尝试运行我的Python代码时,我得到了:
ValueError: column index exceedes matrix dimensions
而当我运行Matlab代码时,这个问题并没有出现,尽管数组的大小超过了定义的矩阵大小...
我到底哪里出错了?显然我搞错了什么... 非常感谢任何帮助!
1 个回答
3
问题是,Python的索引是从 0
开始的,而Matlab的索引是从 1
开始的。所以对于一个大小为 57344
的 数组
,在Python中,第一个元素是 arr[0]
,最后一个元素是 arr[57343]
。
你的变量 j
的值从 1
到 57344
。你可能已经发现了这个问题。像这样创建你的 j
可以解决这个问题:
j = np.floor(np.arange(0,size, dtype=np.double)/expan)
不过,最好在使用之前先检查一下...