Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assignment of matrix through nested loops only works for first row

See the following simplified code

import numpy as np
u=np.zeros((3,3))
i,j=0,0
while i<3:
    while j<3:
        u[i,j]=i+j
        j=j+1
    i=i+1

I was expecting a full matrix u (except for [0,0] element). This code seems to assign to only first row of u. I have used something like this in MATLAB in the past with success

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The main problem is that you forgot to reset the index j when the inner loop is complete. After the first row, j will be greater than 3 so u[i, j] will not make sense.
The correct code would be:

import numpy as np
u=np.zeros((3,3))
i=0
while i<3:
    j=0
    while j<3:
        u[i,j]=i+j
        j=j+1
    i=i+1

This should fix your issue and initialize u to the following array:

[[0. 1. 2.]
 [1. 2. 3.]
 [2. 3. 4.]]

Note that although the code is correct, it could be rewritten to be a bit cleaner using for loops and ranges:

import numpy as np
u = np.zeros((3, 3))
for i in range(3):
    for j in range(3):
        u[i, j] = i+j
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading