# Construct a matrix using a for loop

## Question:

I have calculated 9 matrix elements named sij, with i and j being variables (i,j = [1, 2, 3]). Here, i denotes rows and j columns. Suppose I want a 3×3 matrix that consists of the matrix elements s11, s12, … s32, s33 (nine elements in total).

``````s11 = 1
s12 = 2
s13 = 3
(...)
s33 = 9
``````

How can I use for loops to construct a matrix out of these elements? Like this:

``````matrix = [[s11, s12, s13], [s21, s22, s23], [s31, s32, s33]]
``````

So that I get a matrix that looks like this.

``````matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
``````

I would consider renaming the `sij` to `s[i][j]`. Then using them in loops would be trivial.

``````s[1][1] = 1
s[1][2] = 2
s[1][3] = 3
(...)
s[3][3] = 9
``````

Then:

``````matrix = [[s11, s12, s13], [s21, s22, s23], [s31, s32, s33]]
``````

You can have the following two nested loops to construct the matrix.

``````for i in (1,4):
for j in (1,4):
``````

BTW, having a 0 based numbering would be more Pythonic.

You are better off writing an array and reshaping such that you don’t need to type out elements to variables but here is a one-liner

``````>> np.reshape([eval('s{0}{1}'.format(x,y)) for x in range(1,4) for y in range(1,4)], (3,3))
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
``````

We can use this code for creating our desired matrix with for loop:

``````n = int(input('n:'))

for i in range(1,n):

for j in range(1,n):

if i<j:
print(1,end = ' ')
else :

print('0',end = ' ')

print()
``````

Output

``````n:5
0 1 1 1
0 0 1 1
0 0 0 1
0 0 0 0
``````
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.