开发者

Issue converting Matlab sparse() code to numpy/scipy with csc_matrix()

开发者 https://www.devze.com 2023-04-13 01:48 出处:网络
I\'m a bit of a newbie to both Matlab and Python so, many apologies if this question is a bit dumb...

I'm a bit of a newbie to both Matlab and Python so, many apologies if this question is a bit dumb...

I'm trying to convert some Matlab code over to Python using numpy and scipy and things were going fine until I reached the sparse matrix that someone wrote. The Matlab code goes like:

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

Here's my python code (with my thought process) leading up to my attempt at conversion. For a given dataset I was testing with (in both Matlab and Python):

nread = 64

nslice = 28

nphasedmap = 3200

expan = 100

numpoints = 57344

Thus, the length of phaseorigin, s, and j arrays are 5734400 (and I've confirmed the functions that create my phaseorigin array output exactly the same result that Matlab does)

#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

so when I try to run my python code I get:

ValueError: column index exceedes matrix dimensions

This doesn't occur when I run the Matlab cod开发者_Go百科e even though the array sizes are larger than the defined matrix size...

What am I doing wrong? I've obviously screwed something up... Thanks very much in advance for any help!


The problem is; Python indexes start from 0, whereas Matlab indexes start from 1. So for an array of size 57344, in Python first element would be arr[0] and last element would be arr[57343].

You variable j has values from 1 to 57344. You probably see the problem. Creating your j like this would solve the problem:

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

Still, better to check this before using...

0

精彩评论

暂无评论...
验证码 换一张
取 消