1

I want to create a function to iterate through a list and a matrix, and return values based on the formula:

Matrix cell value - list value

The code looks like this:

def calculate(matrix, list):
    out_matrix = np.empty_like(matrix)
    for k in list:
        for i in matrix.shape[0]:
            for j in matrix.shape[1]:
                out_matrix[i,j] = matrix[i,j] - k

    return out_matrix

This code iterates all matrix for each value in list. But I need to increment my values to calculate only once. What I want is to iterate the matrix once, for each position in the list.

For example:

list = [1, 2, 3, 4, 5, 6]

matrix = np.array([(1,2,3),
                   (4,5,6)])

The returned values should be:

matrix[0,0] - list [0] = 1 -1 = 0
matrix[0,1] - list [1] = 2 -2 = 0
.....etc

And the out_matrix will store those values in the same place as the input matrix. Thanks for the help! :)

2 Answers 2

2

You can avoid all the messy loops by doing something like:

(matrix.ravel() - np.asarray(list)).reshape(matrix.shape)
Sign up to request clarification or add additional context in comments.

3 Comments

I want to keep all process as a function, as Nhor posted. Thank you for the suggestion!
@Litwos There's not only 'copy and paste it all from SO' ... adding def calculate(matrix, list): return ... in front of my code would give you a function as well (significanlty more efficient, if your matrices are bigger).
Thank you. I am still learning Python, and I tend to use the easiest to understand solutions. I will try implementing your answer as well. :)
1

You should use two loops for this. Use this formula for getting the correct list element i * matrix.shape[1] + j. Also as far as I know numpy.ndarray.shape is an int you should include range in your loops. Try:

def calculate(matrix, list):
    out_matrix = np.empty_like(matrix)
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            out_matrix[i, j] = matrix[i, j] - list[i * matrix.shape[1] + j]

    return out_matrix

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.