Home > database >  Adding text in a sentence using a Python for loop
Adding text in a sentence using a Python for loop

Time:11-21

I am trying to write a simple addition formula which should add a set of matrices based on start and end numbers.

Example:

I have following variables

startNum = 1
EndNum = 4

I would like my formula to be:

Matrix 1 Matrix 2 Matrix 3 Matrix 4

if 
startNum = 1
EndNum = 2

I would like my formula to be:

Matrix 1 Matrix 2

Can you please kindly assist me with this?

CodePudding user response:

Let me know if I interpreted your question right because I'm not exactly sure what you're asking.

You have a list or array of matrices matrices_list = [matrix_1, matrix_2, matrix_3...]and you want to add some of them based on index. Each is a numpy array of the same shape.

import numpy as np    

new_matrix = np.zeros(matrices_list[0].shape)
for i in range(startNum, endNum 1): 
    new_matrix = new_matrix   matrices_list[i]

for startNum=1 and endNum=2 you will get new_matrix = matrix_1 matrix_2.

You may want to add a line to check if endNum is equal to or less than the length of matrices_list.

  • Related