How do I slice an array column-wise within a for loop, adding a new column from the array to a new array for each iteration?

Viewed 97

I'm transcribing an Orthogonal Matching Pursuit algorithm from MATLAB to Python, and I'm having trouble with a specific part of the code.

The Matlab code is:

indx=zeros(L,1);
for j=1:1:L
     proj=D'*residual;
     [maxVal,pos]=max(abs(proj));
     pos=pos(1);
     indx(j)=pos;
     a=pinv(D(:,indx(1:j)))*x;
     residual=x-D(:,indx(1:j))*a;

What I have for Python so far is:

indx = np.zeros([L,], dtype=int)
for j in range(L):
    proj = D.T @ resid
    maxVal, pos = np.amax(np.absolute(proj)), np.argmax(np.absolute(proj), axis = 0)                
    indx[j] = pos               
    d = D[:, indx[j]]
    a = np.linalg.pinv(d) @ x  # take pseudo-inverse of array D and matrix multiply by x
    resid = np.subtract(x, d * a)

My problem starts with not being able to create an empty array in Python of undetermined size like you can in MATLAB. For example, I haven't found a satisfactory replication of how MATLAB creates an empty array ( a = [] ) in Python or Numpy. For right now, I have a initialized as a = [] above the provided code. That's another matter, I think, but in this context a solution to that will help me later on.

To describe what the code is doing in MATLAB a bit, L = 2, so if j = 1 for the first iteration, D(:,indx(1:j)) will be a 34x1 matrix with column indx(1)(which can be any integer from 1 to 80 inclusive) filling the 34 rows. The next iteration will be another column selected from D, which will make D(:,indx(1:j)) a 34x2 matrix with both columns intact.

I separated slicing into the variable d in the python version for clarity. Currently, it overwrites the previously selected column with the new number from indx on the second iteration. I really just don't quite know where to go from here. I've tried several different ways of slicing, but none of them work. The closest I've come to getting what I want is setting indx = np.zeros([L,], dtype=int) and d = D[:,indx[j]], which gives indx.shape = (2,), but because 0 is an index in Python, the first iteration selects the 0th column of D, so I get the 34x2 array, but with a prematurely selected/added column. If I do d = D[:, indx[0:j]], I get an empty 34x0 array for d.

1 Answers

I think there may some information missing, but for your first issue, numpy can initialise an empty array using np.empty you may be able to explore whether that can help you.

For your second issue I am assuming from what you are writing that you want to get increasing number of columns from the array with each index. If so, you can use d = D[:, 0:indx+1] where indx an integer of the row you want

Related