Nam Kang - 1 year ago 48

Python Question

Apologies in advance to those who has to read through my poor coding skill

The objective of this coding is to first develop a 17x17 matrix and solve for the 17 unknowns using methods presented in linear algebra.

The part I am having the most difficulty is:

- implementing 2 counters i and j, where the value of i will increase once the value of j reaches its limit and goes back to 0 again.
- Lastly, being able to insert new values to a single array for later manipulation. I tried using np.insert, np.hstack, np.vstack, np.append, etc could not work it.

So i can generate matrix that looks like

`x11 x12 x13....x1j`

x21 .......... x2j

xi1............xij

here is some attempt

`import numpy as np`

import math as mt

r=[2,2.8,3.2,3.5,3.7,3.8,3.8,3.8,3.8,3.8,3.8,3.8,3.7,3.5,3.2,2.8,2]

n=np.linspace(1,17,17)

m=np.linspace(1,17,17)

i=0

k=np.array([])

l=1

k2=[]

while i <=18:

for j in range(17):

h1=mt.sqrt(r[i]**2+(l*(n[i]-m[j])+l/2)**2)

h2=mt.sqrt(r[i]**2+(l*(n[i]-m[j])-l/2)**2)

h=h1-h2

k2.append(h)

i=i+1

I am trying to obtain stokes' stream function in axially symmetrical flow for those who are interested,

I will appreciate any type of feedback, please guide me in the right direction

Answer

So your code suffers from two mistakes. The first that in python, you start counting from zero; you may think of your matrix as having 17 rows, 1 to 17, but python sees it as going from 0 to 16. The second is that when working with numpy, you should build your array first, and then insert your calculated values. There's a good explanation of why here:(How do I create an empty array/matrix in NumPy?).

I made r an array for consistency's sake, and I inserted the calculated values into k2. I'm not sure k was for.

```
import numpy as np
import math as mt
r=np.array([2,2.8,3.2,3.5,3.7,3.8,3.8,3.8,3.8,3.8,3.8,3.8,3.7,3.5,3.2,2.8,2])
n=np.linspace(1,17,17)
m=np.linspace(1,17,17)
l=1
k2 = np.empty(shape=(17,17))
i=0
j=0
while i <=16:
while j<=16:
h1=mt.sqrt(r[i]**2+(l*(n[i]-m[j])+l/2)**2)
h2=mt.sqrt(r[i]**2+(l*(n[i]-m[j])-l/2)**2)
h=np.array(h1-h2)
k2[i,j]= h
j+=1
j=0
i+=1
```

I hope this was helpful to you, and good luck with your python practicing. Please up vote if this was of help to you.