Python Forum

Full Version: Matrix Calculation Problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to add array numbers in nested for loop.
inner loop depends on outer loop. It give me some unexpected results. Following is my code please check and guide me about that problem

import numpy as np

n=5
A=np.zeros([n,n])
B=np.zeros([n])
sum=0
for i in range(n):
    for j in range(n):
        A[i][j]=i-j

for i in range(1,n):
    for j in range(i-1):
        B[i]+=sum+A[i][j]

print(B)
Output:
[0. 0. 2. 5. 9.]
I need the following result
Output:
[0, 1, 2, 5, 9]
Why do you expect the result to be [0, 1, 2, 5, 9]? What do you want to sum exactly?
for i in range(1,n):
    for j in range(i-1):
        B[i] += sum + A[i][j]
In the first iteration of the loops i equals 1 therefore "j in range(0)" is not executed and B[1] is never updated.
Why j in range(0) is not excuted because it value present in array A. i.e A[1][0]. why the code doesnot pick this value?

(Nov-04-2019, 09:20 AM)Gribouillis Wrote: [ -> ]Why do you expect the result to be [0, 1, 2, 5, 9]? What do you want to sum exactly?

I want to add the array elements row wise.
when i=1 then range of j is 0. so according to the code
B[1]+=A[1][0]
for i=2 the range for j is 1.
B[2]+=A[2][1]
for i=3, j=0, 1, 2
B[3]+=A[3][0]+A[3][1]+A[3][2]
Actually i want the above mentioned sum

the code give correct result for i=2, 3 and 4 but not for i=1.
i want the code execute for i=1 also

(Nov-04-2019, 09:07 AM)arshad Wrote: [ -> ]I want to add array numbers in nested for loop. inner loop depends on outer loop. It give me some unexpected results. Following is my code please check and guide me about that problem
import numpy as np n=5 A=np.zeros([n,n]) B=np.zeros([n]) sum=0 for i in range(n): for j in range(n): A[i][j]=i-j for i in range(1,n): for j in range(i-1): B[i]+=sum+A[i][j] print(B)
Output:
[0. 0. 2. 5. 9.]
I need the following result
Output:
[0, 1, 2, 5, 9]

ok sorry i will do this next time thanks
(Nov-04-2019, 02:55 PM)arshad Wrote: [ -> ]Why j in range(0) is not excuted because it value present in array A. i.e A[1][0]. why the code doesnot pick this value?

range(0) returns a 0. That means that it will NOT iterate (or it will iterate 0 amount of times) and it goes directly to the next iteration on the upper loop where i=2.


This check outputs what you were asking for:
for i in range(n):
    if i <= 1:
        value=1
    else:
        value=i-1
    for j in range(value):
        B[i] += sum + A[i][j]
Output:
[0. 1. 2. 5. 9.]