Loop across K-uplets from a N-K matrix in python - python

I have to use dynamic programming in a python script.
I defined a numpy array u with shape=(N,K).
I want to pick one element for each column, therefore generating a K-uplets.
How would you proceed to loop efficiently across all K-uplets generated this way ? A solution would be to use
import itertools
itertools.combination_with_replacement(list,K)
where list = [0..N-1], but I will need to build iteratively each of my K-uplets using the output (index) of the itertools method.
Is there a more direct way to proceed ?
Thanks
Vincent

You can build the K-uplet with arr[ind, np.arange(K)]. Of course, that's actually a NumPy ndarray, but they are easy to convert to tuplets if you really want tuplets: tuple(arr[ind, np.arange(K)]).
import numpy as np
import itertools as IT
N, K = 5,3
arr = np.arange(N*K).reshape(N,K)
print(arr)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]
# [12 13 14]]
for ind in IT.combinations_with_replacement(range(N), K):
print(arr[ind, np.arange(K)])
# [0 1 2]
# [0 1 5]
# [0 1 8]
# [ 0 1 11]
# ...

Related

Solving a matrix with Crammers Rule in python [duplicate]

This question already has answers here:
Numpy array assignment with copy
(3 answers)
Closed 6 months ago.
I'm trying to make a function where I can give it a matrix and the constants and solving it using crammers rule. This will soon be used with complex numbers.
import numpy as np
import sympy as smp
def crammer(matrix, constants):
D = np.linalg.det(matrix)
dets = []
dets.append(D)
for i in range(0, len(constants[0]), 1):
Dv = matrix
Dv[:, i:i+1] = constants.T
print(Dv)
Dd = np.linalg.det(Dv)
dets.append(Dd)
return dets
Mat = np.array([[2, 1,-1],
[3, 2, 2],
[4,-2, 3]])
Con = np.array([[1,13,9]])
print(crammer(Mat, Con))
I get this as the result:
[33.000000000000014, 33.000000000000014, 0.0, 0.0]
The first two are right the Determinate is D:33 and Dx:33 but Dy and Dz should be Dy:66 and Dz: 99.
following Crammers Rule it should be:
[[ 1 1 -1]
[13 2 2]
[ 9 -2 3]]
[[ 2 1 -1]
[ 3 13 2]
[ 4 9 3]]
[[ 2 2 1]
[ 3 2 13]
[ 4 -2 9]]
when I print Dv at the beginning of the for loop I get the following:
[[ 1 1 -1]
[13 2 2]
[ 9 -2 3]]
[[ 1 1 -1]
[13 13 2]
[ 9 9 3]]
[[ 1 1 1]
[13 13 13]
[ 9 9 9]]
I tried printing the matrix at the top of the for loop as well and I get the same problem. As I can tell my for loop is is changing my original matrix and I don't understand why.
Unsure what the algorithm itself is trying to accomplish, but from a Python perspective, by assigning Dv = matrix, you're creating a shallow copy by reference that then gets modified by the rest of the code in the loop.
I replaced this assignment with Dv = deepcopy(matrix) (use from copy import deepcopy) to create a deep copy, fresh from the original matrix.
That produced this result, which seems in line with what you predicted:
[33.000000000000014, 33.000000000000014, 66.00000000000003, 99.00000000000007]
copy documentation

Applying a function along a numpy array using indexes as parameters

I am trying to find a way to run a function through a whole ndarray using the indexes of every value as parameters. A regular loop is quite slow and I can't find a way to make it work using numpy built-in functions. The next example code summarizes what i'm trying to do. Thanks in advance.
import numpy as np
arr = np.arange(10).reshape(2, 5)
print(arr)
def example_func(row, col, value):
return(row + col + value)
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
arr[row, col] = example_func(row, col, arr[row, col])
print(arr)
[[0 1 2 3 4]
[5 6 7 8 9]]
[[ 0 2 4 6 8]
[ 6 8 10 12 14]]
What you try to do can be done with meshgrid.
Return coordinate matrices from coordinate vectors.
n_rows, n_cols = arr.shape
col_matrix, row_matrix = np.meshgrid(np.arange(n_cols), np.arange(n_rows))
result = arr + col_matrix + row_matrix
print(result)
This returns
[[ 0 2 4 6 8]
[ 6 8 10 12 14]]

Iterate through upper triangular matrix in Python

I am using Python and I have a XxY matrix where X=Y and I want to iterate over the upper triangular matrix in a specific way such that it starts with and proceeds with and and so on and so forth until the last row and column. Therefore, I tried to create a double loop which loops over the columns one by one and within that loop I created another loop which loops over the rows always adding one row. However, I got stuck in defining how to add the next row for every column in the second loop. Here is what I got so far (for simplicity I just created an array of zeros):
import pandas as pd
import numpy as np
# number of columns
X = 10
# number or rows
Y = X
U = np.zeros((Y,X))
for j in range(X):
for z in range():
My initial idea was to create an array of Yx1 with y = np.asarray(list(range(0,Y)))and use it for the second loop but I don't understand how to implement it. Can somebody please help me? Is there maybe a simpler way to define such an iteration?
With Numpy, you can get the indices for the upper triangular matrix with triu_indices_from and index into the array with that:
import numpy as np
a = np.arange(16).reshape([4, 4])
print(a)
#[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
indices = np.triu_indices_from(a)
upper = a[indices]
print(upper)
# [ 0 1 2 3 5 6 7 10 11 15]

how to make rank array in numpy

Given a numpy ndarray A, return its rank array.
Input : [[ 9 4 15 0 18]
[16 19 8 10 1]]
Return value: [[4 2 6 0 8]
[7 9 3 5 1]]
**but I didnt solve actually I solve but my solution is wrong
how can I solve ? please help meemphasized text**
import numpy as np
array=np.array([[9,4,15,0,18],[16,19,8,10,1]])
array_1=np.array([9,4,15,0,18])
array_2=np.array([16,19,8,10,1])
temp1 = array_1.argsort()
temp2 = array_2.argsort()
ranks1 = np.arange(len(array_1))[temp1.argsort()]
rankss=ranks1.argsort()
ranks2 = np.arange(len(array_2))[temp2.argsort()]
print(ranks1*array.ndim)
print(rankss)
If you pass axis=None to argsort then the source array
is flattened at the first step (and only then arg-sorted).
So probably the shortest code is:
result = arr.argsort(axis=None).reshape(arr.shape)
No need to explicitely flatten the source array and only
a single call to argsort.

Creating new numpy matrix from list of rows of existing matrix

I have a 2D numpy array A, and a list x. The elements of x are indices of the rows of A. I want to create a new matrix B, by taking the rows of A as indicated by x. How can I do this?
You can pass x as an argument when indexing A to create your new matrix B as below. See the docs here.
import numpy as np
A = np.arange(25).reshape((5,5))
x = [1, 2, 4]
B = A[x]
print(B)
# [[ 5 6 7 8 9]
# [10 11 12 13 14]
# [20 21 22 23 24]]

Categories

Resources