Search code examples
pythonmatlabnumpymatrixvalueerror

Setting matrix elements equal to sub list


What is the python equivalent of copying indexed elements from a list to an existing array. This is the matlab code below to recreate in Python:

N = 5
cov_mat = ones(N, N+1)*-1
row = 1:1:N;
for n=1:N
    cov_mat(n, 1:N+1-n) = row(n:N);
end

Solution

  • You forgot to show us what the MATLAB code does. My MATLAB memory is dated, so I can't readily run it in my head :(

    In an Octave session:

    >> N=5;
    >> cov_mat = ones(N,N+1)*-1;
    >> row=1:1:N;
    >> row
    row =
    
       1   2   3   4   5
    
    >> cov_mat(1,1:N+1-1) = row(1:N);
    >> cov_mat
    cov_mat =
    
       1   2   3   4   5  -1
      -1  -1  -1  -1  -1  -1
      -1  -1  -1  -1  -1  -1
      -1  -1  -1  -1  -1  -1
      -1  -1  -1  -1  -1  -1
    
    >> cov_mat(2,1:N+1-2) = row(2:N);
    >> cov_mat(3,1:N+1-3) = row(3:N);
    >> cov_mat
    cov_mat =
    
       1   2   3   4   5  -1
       2   3   4   5  -1  -1
       3   4   5  -1  -1  -1
      -1  -1  -1  -1  -1  -1
      -1  -1  -1  -1  -1  -1
    

    So you set all to -1, and then fill a triangle with slices of the range.

    A numpy equivalent (after a bit of trial and error to get the indices right):

    In [134]: N=5
    In [135]: res = -np.ones((N,N+1),int)
    In [136]: for i in range(N):
         ...:     res[i,:N-i]=1+np.arange(i,N)
         ...: 
         ...: 
    In [137]: res
    Out[137]: 
    array([[ 1,  2,  3,  4,  5, -1],
           [ 2,  3,  4,  5, -1, -1],
           [ 3,  4,  5, -1, -1, -1],
           [ 4,  5, -1, -1, -1, -1],
           [ 5, -1, -1, -1, -1, -1]])
    

    In both languages it would be nice to avoid the row iteration, but it's probably not worth the effort.

    We can index the triangular values with:

    In [145]: res[np.arange(5)[:,None]<np.arange(6)[::-1]]
    Out[145]: array([1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5])