• (2 Pages)
• 1
• 2

## 15 Replies - 705 Views - Last Post: 01 October 2019 - 11:47 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=417395&amp;s=88aff21538de7c2ee169f9347ed59d3e&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

Posted 25 September 2019 - 11:49 AM

Hi,

I'm a begginer and having trouble adding matrices with python. Can someone help (my code is not working and I don't know why). See below:

```def main(lines, colunes, value):

matrice=[]

for i in range(lines):
line=[]
for j in range(colunes):
line.append(value)

matrice.append(line)

return matrice

def soma_matrices(A,B ):
num_lin = len(A)
num_col = len(A[0])
C = matrice.cria_matrice(num_lin, num_col, 0)

for lin in range(num_lin):
for col in range(num_col):
C[lin][col] = A[lin][col] + B[lin][col]

return C

if __name__ == '__main__':
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[100, 200, 300], [400, 500, 600], [700, 800, 900]]
print(soma_matrices(A,B ))

main()
```

This post has been edited by modi123_1: 25 September 2019 - 11:56 AM
Reason for edit:: the future, please use the [code] tag button in the editor.

Is This A Good Question/Topic? 0

## Replies To: Add matrices in python

### #2 modi123_1

• Suitor #2

Reputation: 15359
• Posts: 61,588
• Joined: 12-June 08

## Re: Add matrices in python

Posted 25 September 2019 - 11:56 AM

Please explain what isn't work, and in what way.

### #3 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

## Re: Add matrices in python

Posted 25 September 2019 - 12:01 PM

Hi modi, thank you for replying to me. Here's what I get from the shell:

Traceback (most recent call last):
File "C:/Users/DELL/Documents/Trabalho/soma matrizes.py", line 31, in <module>
print(soma_matrizes(A,)
File "C:/Users/DELL/Documents/Trabalho/soma matrizes.py", line 20, in soma_matrizes
C = matrice.cria_matriz(num_lin, num_col, 0)
NameError: name 'matrice' is not defined

### #4 modi123_1

• Suitor #2

Reputation: 15359
• Posts: 61,588
• Joined: 12-June 08

## Re: Add matrices in python

Posted 25 September 2019 - 12:06 PM

Mkay.. so it looks to be a scope issue.

You define a variable inside the method 'main'.
```03    matrice=[]
```

.. but inside the other method "def soma_matrices" isn't in the same scope as "main".
```18    C = matrice.cria_matrice(num_lin, num_col, 0)
```

So you need to think about defining a variable differently or in a different level of scope.. like 'global'.

### #5 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

## Re: Add matrices in python

Posted 25 September 2019 - 12:29 PM

thanks, modi. Bu just pulling the matrice=[] to before the main funccion isn't working either.

### #6 modi123_1

• Suitor #2

Reputation: 15359
• Posts: 61,588
• Joined: 12-June 08

## Re: Add matrices in python

Posted 25 September 2019 - 12:34 PM

Not working in the same way, or what?

You know just calling a variable 'matrix' doesn't make it a matrix.

Looks like a plain list right now.

Plus, no idea what 'cria_matrice' is.

### #7 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

## Re: Add matrices in python

Posted 25 September 2019 - 12:45 PM

I know, otherwive I wouldn't write the funccions in the first place. thank you, anyway, for your help.

### #8 modi123_1

• Suitor #2

Reputation: 15359
• Posts: 61,588
• Joined: 12-June 08

## Re: Add matrices in python

Posted 25 September 2019 - 01:11 PM

*shrug* Not sure what that means, but good luck I guess.

### #9 DK3250

• Pythonian

Reputation: 561
• Posts: 1,794
• Joined: 27-December 13

## Re: Add matrices in python

Posted 25 September 2019 - 04:15 PM

Your code never get to call 'main()', line 31 - it stops in the function called in line 29.

In the function it terminates because (as mentioned my modi123_1) line 18 is bad.

Also note that your main requires three arguments.

I know you're a beginner, but let me offer this:
```A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[100, 200, 300], [400, 500, 600], [700, 800, 900]]

D = [[c0+c1 for c0, c1 in zip(c[0], c[1])] for c in zip(A, B )]

print(D)

output:
[[101, 202, 303], [404, 505, 606], [707, 808, 909]]

```

This is made by double list comprehensions, not easy stuff; the code is equivalent to this:
```A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[100, 200, 300], [400, 500, 600], [700, 800, 900]]

C = zip(A, B )  # make pair line elements from the two matrices
D = []  # make empty result matrix
for c in C:  # from each pair of line elements...
d = []  # make empty line
for c0, c1 in zip(c[0], c[1]): # ... extract pairs of single values
d.append(c0 + c1)  # add the single values sum to line
D.append(d)  # add line to result matrix

print(D)
```

### #10 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

## Re: Add matrices in python

Posted 26 September 2019 - 04:35 AM

thank you so, so much!!!

### #11 DK3250

• Pythonian

Reputation: 561
• Posts: 1,794
• Joined: 27-December 13

## Re: Add matrices in python

Posted 26 September 2019 - 11:36 AM

Just for the records:
I've re-worked the code from post #9 with the intention to make it more pedagogic:
```A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[100, 200, 300], [400, 500, 600], [700, 800, 900]]

# The comprehensive form:
D = [[a+b for a, b in zip(*c)] for c in zip(A, B )]
print(D)

#The loop form:
D = []

for a_row, b_row in zip(A, B ):
row_sum = []
for a_val, b_val in zip(a_row, b_row):
row_sum.append(a_val + b_val)
D.append(row_sum)

print(D)
```

In the loop form, I have changed variable names to (hopefully) more descriptive ones.
Also, the tuple unpacking is moved from second for-loop to the first one.

In the list comprehension form the tuple unpacking is made by use of an Asterix ('*').

### #12 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

## Re: Add matrices in python

Posted 26 September 2019 - 02:27 PM

Thanks, again, for teaching me a new command that I'll be using often (zip). Also for teaching me a new way to look at the problem that was easy enough to understand. Still catching up with all this code sintaxe, however.

This post has been edited by andrewsw: 27 September 2019 - 06:04 AM

### #13 Choscura

• D.I.C Lover

Reputation: 478
• Posts: 2,267
• Joined: 18-October 08

## Re: Add matrices in python

Posted 01 October 2019 - 07:45 AM

Matrix programming is NOT where you should start with your first-ever-basic-program. You should start with something that you can *actually use*, and then when you know how *THAT* works, then you should try doing that with shitty-imperfect-tools-designed-to-let-programmers-hack-with-math-they-already-know. you're not a programmer <YET!> and don't know this math yet- you don't start "the topic of English writing" trying to copy Shakespheare, and that's kind of what you're asking for.

But if you're interested in the topic, then what you want to read up on is called "linear algebra" for the math part <because you have to know which sort of equation is which, and what they're supposed to do, so that you can properly assign the program to do this>, and the book "3D Math Primer for Graphics and Game Development" by Dunn and Parberry.

the python side of this, I'd probably use the same [] list structure, *maybe* I'd go as far as having lists of lists [[,,]], but I'd add handling to validate if the values in it are actually valid matrix values going in/ if they make sense being pulled out.

### #14 AraxaP

Reputation: 0
• Posts: 8
• Joined: 25-September 19

## Re: Add matrices in python

Posted 01 October 2019 - 10:44 AM

Hi, thanks for replying to me. I'm doing an oline course on python and after 8 weeks am doing this lesson. Haven't done anything near practical with what i've learned. Nor have I ever took any interest in machines/ computers before in my life. The course is all about loops and nested loops. But don't know if the math is exactly the problem. More likely the language itself. Will buy the book, however. Thanks a lot.

### #15 DK3250

• Pythonian

Reputation: 561
• Posts: 1,794
• Joined: 27-December 13

## Re: Add matrices in python

Posted 01 October 2019 - 10:48 AM

@Choscura:
Hm, In my view there's nothing wrong in programming a linear algebra task as unexperienced programmer.
Actually, it's my impression that OP understands the relevant math - but struggles with coding primarily.

There is more than one 'python side of this'; list, nested list, list comprehension has already been brought in play.
But the Numpy library is probably where a professional would turn for linear algebra.
This is the efficient way but without much learning of python language.