Home > Software engineering >  Python iterate through a matrix
Python iterate through a matrix

Time:12-01

I have a function which computes some results for all combinations of the values in the input vector:

MyFunction(inp_vec):
    ...
    return some_array

inp_vec can be a list of any length between 1 and 6. The output array some_array can therefore be of any size between (1,1) and (6,6), respectively.

For some further calculations, I'd like to assemble an array of size (6,6), which would be composed of all zeros at first A = np.empty([6,6]), and the respective entries, as computed by the function, would be replaced with some values.

The problem is that the output array some_array can be of a size different than (6,6).

I'd like to use something like numerate(), but within this kind of for loop:

for i,j in list(itertools.product(inp_vec, inp_vec)):
    A[n,m] = some_array[i, j]

How do I get the iterators n, m?

CodePudding user response:

I think this is what you want:

import numpy as np
import itertools
inp_vec = np.array([1,2,3])
A = np.empty([6,6])

M = np.array(list(itertools.product(inp_vec, inp_vec))).reshape(len(inp_vec),-1,2)
print(M)

output:

[[[1 1]
  [1 2]
  [1 3]]

 [[2 1]
  [2 2]
  [2 3]]

 [[3 1]
  [3 2]
  [3 3]]]

CodePudding user response:

Finally solved by introducing iterators n and m inside the for loop, mapping between the entries in output array and the target array:

for i,j in itertools.product(some_array_indices, some_array_indices):
    m = inp_vec_indices[i]
    n = inp_vec_indices[j]
    A[m][n] = float(some_array[i][j])
  • Related