 # Matrix initialization

Hello

I am doing a simple matrix addition within 2 nested for loops
The main syntax is mat_c[i][j]=mat_a[i][j] + mat_b[i][j]

This runs in to an error saying mat_c is not initialized

How do I initialize it when I dont know what the dimension of mat_c is going to be ?

Thanks
Harish

Looks like I need to initialize this way although I did not quite understand the syntax of it
#Initialize a matrix

mat = [[0 for i in range(2)] for j in range(2)]

print(mat)

it is an implementation choice.
You can init a 2-D list the way you did, and update each element referenced by their index.
OR
You can create a 1-D List first. Then append that with lists again.
Example:

``````a = [[1,1],[1,1]]
b = [[1,1],[1,1]]
c = []
print (a)
print (b)
print (c)

for i in range(2):
temp = []
for j in range(2):
temp.append(a[i][j] + b[i][j])
c.append(temp)
print(c)
``````

`mat = [[0 for i in range(2)] for j in range(2)]`
This single line of code is conceptually the equivalent of the following multi line code:

``````mat=[]
for j in range(2):
temp=[]
for i in range(2):
temp.append(0)
mat.append(temp)
``````

Hope this helps

Great. This is very good and very helpful