-1

Need to converge two matrix value together in form of tuple .

  1. Matrix

0 1 2 3

1 1 1 1

2 2 1 3

3 2 3 1

  1. Matrix

0 1 2 3

1 4 6 7

2 3 5 6

3 1 3 5

Output required is

0 1 2 3

1 (1,4) (1,6) (1,7)

2 (2,3) (1,5) (3,6)

3 (2.1) (3,3) (1,5)

where first row and column is index of the matrix.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • 2
    How are your matrices stored? As list or lists or numpy arrays? – James Feb 07 '22 at 14:43
  • Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – Tomerikoo Feb 07 '22 at 15:12
  • Please provide enough code so others can better understand or reproduce the problem. – Community Feb 17 '22 at 13:11

1 Answers1

0

Assuming your matrix is list of lists, you can use zip() -

from random import randint
a = [[randint(1, 10) for _ in range(3)] for _ in range(3)]
b = [[randint(1, 10) for _ in range(3)] for _ in range(3)]
c = [list(zip(x, y)) for x, y in zip(a, b)]
>>> a
[[8, 4, 1], [4, 3, 4], [2, 5, 5]]
>>> b
[[2, 2, 1], [6, 1, 7], [10, 3, 5]]
>>> c
[[(8, 2), (4, 2), (1, 1)], [(4, 6), (3, 1), (4, 7)], [(2, 10), (5, 3), (5, 5)]]

If you don't want to use zip, using list comprehension -

c = [list((a[i][j], b[i][j]) for j in range(len(a[0]))) for i in range(len(a))]

Both ways work even when a and b is not square matrix as long as the dimensions of both matrices are identical.

Jay
  • 2,431
  • 1
  • 10
  • 21