0

User can enter any value & the program will print the final matrix. Here I have used matrix addition to display the matrix in 3x3 form. I want to know is there any short way to still get our matrix in 3x3 form?

Here's my code:

print('Consider matrix mij with i rows & j colomns:')
a=int(input('Enter m11 value: '))
b=int(input('Enter m12 value: '))
c=int(input('Enter m13 value: '))
d=int(input('Enter m21 value: '))
e=int(input('Enter m22 value: '))
f=int(input('Enter m23 value: '))
g=int(input('Enter m31 value: '))
h=int(input('Enter m32 value: '))
i=int(input('Enter m33 value: '))
X=[[a,b,c],
   [d,e,f],
   [g,h,i]]
Y=[[0,0,0],
   [0,0,0],
   [0,0,0]]
print('Your matrix is:')
for i in range(len(X)):
    for j in range(len(X[0])):
        X[i][j]=X[i][j]+Y[i][j]
for r in X:
    print(r)
Rachit
  • 75
  • 1
  • 5

4 Answers4

1

Indeed, you can use f-strings to achieve this.

print(f"[{X[0][0]} {X[0][1]} {X[0][2]}]\n[{X[1][0]} {X[1][1]} {X[1][2]}]\n [{X[2][0]} {X[2][1]} {X[2][2]}]")

Take this sample:

f"[{X[0][0]} {X[0][1]} {X[0][2]}]\n"

Here, the values inside the {} are replaced by the expression inside. The \n acts as a special character which continues the print on a newline.

You can take inputs quicker using this code:

X = [[input(f"Enter m{i}{j}: ") for j in range(3)] for i in range(3)]

This is called list comprehension and you can extend this to take as many values as you want.

Bhavye Mathur
  • 1,024
  • 1
  • 7
  • 25
0
fm=list(map(int,input().split())) //first matrix
sm=list(map(int,input().split())) //second matrix
print("answer:")
for i in range(9):
    print(fm[i]+sm[i],end=' ')
    if i%3==2:
        print()
Abu Saeed
  • 1,020
  • 8
  • 21
0

one possible solution is using numpy:

import numpy as np
a=1
b=2
c=3
d=4
e=5
f=6
g=7
h=8
i=9
X=[[a,b,c],
   [d,e,f],
   [g,h,i]]

print(np.matrix(X))

the out put is:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

Stefan Schulz
  • 533
  • 3
  • 8
  • Worth noting the comment in [the documentation for np.matrix](https://numpy.org/doc/stable/reference/generated/numpy.matrix.html) *"It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future."* – David Buck Sep 22 '20 at 14:54
0

Use comprehension to compress your answer for example: [i for i in range[condition]]

using comprehension may help you

Bhavye Mathur
  • 1,024
  • 1
  • 7
  • 25