0

I need to work with a matrix. You should be able to input numbers in matrix (for example if i need to have 1 on the diagonal and 0.6 up and under the diagonal i can just input it, 0.6 is only on the line under the diagonal). It has a simple solution but gets tricky when i also want to edit size of the matrix.

Im using numpy library

Jatel
  • 40
  • 8
  • Can you please provide some example of what you've already done, also what the input and output should look like. – pajamas Dec 10 '21 at 14:02

1 Answers1

0

If you want a matrix like this:

[1. , 0.6, 0.6, 0.6, 0.6]
[0.6, 1. , 0.6, 0.6, 0.6]
[0.6, 0.6, 1. , 0.6, 0.6]
[0.6, 0.6, 0.6, 1. , 0.6]
[0.6, 0.6, 0.6, 0.6, 1. ]
import numpy as np

# First, you create a matrix full of the numbers outside the diagonal (let's use 5 as an example of the matrix' shape)

matrix = np.full((5,5),0.6)

# Then, you can edit the diagonal but using "numpy.diag_indices_from":

matrix[np.diag_indices_from(matrix)] = 1

print(matrix)

Out:

array([[1. , 0.6, 0.6, 0.6, 0.6],
       [0.6, 1. , 0.6, 0.6, 0.6],
       [0.6, 0.6, 1. , 0.6, 0.6],
       [0.6, 0.6, 0.6, 1. , 0.6],
       [0.6, 0.6, 0.6, 0.6, 1. ]])
Dharman
  • 30,962
  • 25
  • 85
  • 135
femdias
  • 33
  • 1
  • 6
  • thanks, but is there some way to acces numbers under the diagonal ? i dont meen all the numberes there just the line under the diagonal – Jatel Dec 12 '21 at 09:05
  • @Jatel by "the line under the diagonal" you mean the 'other diagonals'? If that correct, there a post with some answers about this problem: https://stackoverflow.com/questions/6313308/get-all-the-diagonals-in-a-matrix-list-of-lists-in-python – femdias Dec 13 '21 at 14:32