1

Create a 4 x 4 matrix and add values 4,5,6 above the parent diagonal.I'm unable to understand how to achieve this output. Tried diagonal method but failed. I want the output as shown below.

            [[0 4 0 0]
             [0 0 5 0]
             [0 0 0 6]
            [0 0 0 0]]

2 Answers 2

3
In [120]: np.diag([4,5,6],1)
Out[120]: 
array([[0, 4, 0, 0],
       [0, 0, 5, 0],
       [0, 0, 0, 6],
       [0, 0, 0, 0]])
4
  • 1
    Please add some context to the code snippet for the benefit of the future readers. Dec 24, 2018 at 9:27
  • What kind of context does it need? It does the job, and the function is documented.
    – hpaulj
    Dec 24, 2018 at 9:57
  • Your answer landed in VLQ. As per best practices I just suggested a step to make the content useful the future readers. Dec 24, 2018 at 10:00
  • Evidently someone is more concerned with appearance than content of my post. Given the title and minimal tags I don't expect many future readers. The context provided by the question is sufficient.
    – hpaulj
    Dec 24, 2018 at 17:45
1

I don't know if this is active or not, but I found a different, bit complicated way to achieve the same and just wanted to share with you guys.(I am a beginner Python user):

mat1 = np.zeros((4,4))
list1 = [4,5,6]

for i in range(mat1.shape[1]):
        for j in range(mat1.shape[0]):
            if i<len(list1) and i==j:
                mat1[i][j+1] = list1[i]
print(mat1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.