【问题标题】:Issue converting Matlab sparse() code to numpy/scipy with csc_matrix()使用 csc_matrix() 将 Matlab sparse() 代码转换为 numpy/scipy 的问题
【发布时间】:2011-12-07 08:06:27
【问题描述】:

我对 Matlab 和 Python 都是一个新手,所以如果这个问题有点愚蠢,请多多道歉......

我正在尝试使用 numpy 和 scipy 将一些 Matlab 代码转换为 Python,并且在我到达某人编写的稀疏矩阵之前一切都很好。 Matlab 代码如下:

unwarpMatrix = sparse(phaseOrigin, ceil([1:nRead*nSlice*nPhaseDmap]/expan), 1, numPoints, numPoints)/expan;

这是我尝试转换的 Python 代码(以及我的思考过程)。对于我正在测试的给定数据集(在 Matlab 和 Python 中):

nread = 64
nslice = 28
nphasedmap = 3200
展开 = 100
点数 = 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 代码时,即使数组大小大于定义的矩阵大小,也不会发生这种情况...

我做错了什么?我显然搞砸了……非常感谢您的帮助!

【问题讨论】:

    标签: python matlab scipy sparse-matrix


    【解决方案1】:

    问题是; Python 索引从0 开始,而Matlab 索引从1 开始。所以对于大小为57344array,在Python 中第一个元素是arr[0],最后一个元素是arr[57343]

    变量j 的值从157344。你可能看到了问题。像这样创建j 可以解决问题:

    j = np.floor(np.arange(0,size, dtype=np.double)/expan)
    

    不过,最好在使用前检查一下...

    【讨论】:

    • 嗯...我不认为这是我遇到的问题,因为 len(j) = 5734400 (这是我想要的),我确实想要 j[0] = 1
    • @NJM:j 的长度不是问题,而是max(j) = 57344j 保存列信息,如果用“1”表示第一列,那么您肯定会想要j[0]=0 在 Python 中。检查此链接以了解 Python(numpy 和 scipy)与 Matlab 之间的差异:scipy.org/NumPy_for_Matlab_Users
    • 啊,我明白你现在在说什么了。看起来我可能还需要查看我的 phaseorigin 变量,因为它的 max() 似乎也是 57344.00。谢谢。
    猜你喜欢
    • 2016-01-21
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-12
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多