I need to set up a for loop for an experimental procedure (matrix 10 task) where I need to display 150 4x4 matrix arrays in which a minimum of 2 numbers add up to 10 or 5. It is supposed to look as below. Now I know how to create a matrix and the respective for loop but is there a way to make sure that within an array a specified amount of numbers adds up to a value i.e. 10?
[[1.69 1.82 2.91]
[4.67 4.81 3.05]
[5.82 5.06 4.28]
[6.36 5.19 4.57]]
Thank you
CodePudding user response:
I'm assuming that you're using numpy to create your arrays
Do you have any particular additional rule in the way that your arrays have to be defined ?
A simple way to create such an array is :
import numpy as np
x = np.zeros((4, 4))
x[0,0] = 10
This array indeed corresponds to your definition
Now if you want to make it more random, the best way is to randomly generate the indices in which you want your pair of specific numbers to appear. I'll do that by reshaping a 16x1 array because I'm lazy and I prefer dealing with 1D things
import numpy as np
i,j = np.random.choice(np.arange(16), size=2, replace=False) # Generates two random indices
x = np.random.uniform(low=0, high=10, size=16) # Generates a random array
x[i] = 10-x[j] # Does the trick
x = np.reshape(x, (4, 4)) # Reshapes
CodePudding user response:
The following example assigns random numbers to 2D arrays and prints the array values using a nested for loop. You can develop any algorithm you want using this approach.
import numpy as np
import random
rows = 4
columns = 4
array1 = np.zeros((rows, columns))
array2 = np.zeros((rows, columns))
array3 = np.zeros((rows, columns))
for j in range(columns):
for i in range(rows):
array1[i,j] = random.uniform(0.0, 10.0)
array2[i,j] = random.uniform(0.0, 10.0)
array3[i,j] = random.uniform(0.0, 10.0)
arrays = [array1, array2, array3]
for size in range(len(arrays)):
for j in range(columns):
for i in range(rows):
print("Array: " str(size) " [" str(i) "," str(j) "]: " str(arrays[size][i,j]))
This program prints the value as in the following example:
Array: 0 [0,0]: 0.44105865643185527
Array: 0 [1,0]: 2.622675653268798
Array: 0 [2,0]: 6.779961464306787
...
