Python Forum
Matrix Calculation Problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Matrix Calculation Problem (/thread-22217.html)



Matrix Calculation Problem - arshad - Nov-04-2019

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]



RE: Matrix Calculation Problem - Gribouillis - Nov-04-2019

Why do you expect the result to be [0, 1, 2, 5, 9]? What do you want to sum exactly?


RE: Matrix Calculation Problem - baquerik - Nov-04-2019

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.


RE: Matrix Calculation Problem - arshad - Nov-04-2019

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


RE: Matrix Calculation Problem - baquerik - Nov-04-2019

(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.]