在Julia或python中检索矩阵的顺序删除列(行也被删除)的原始索引

2024-09-30 01:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望在删除前一列的最大和之后,在每次迭代中检索该列的原始索引。同时,在每次迭代时,也会从矩阵中删除已删除列的同一索引行

例如,在10×10矩阵中,第5列的和最大,因此第5列和第5行被删除。现在矩阵是9乘9,重新计算列的总和。假设第6列的和最大,则删除当前矩阵的第6列和第6行,即原始矩阵中的第7列。重复执行此操作,直到保留所需的索引列数

我在Julia中的代码不起作用粘贴在下面for循环中的第二步不正确,因为每次迭代都会删除一行,因此列的总和不同。

谢谢

# a matrix of random numbers
mat = rand(10, 10);
# column sum of the original matrix
matColSum = sum(mat, dims=1);

# iteratively remove columns with the largest sum
idxColRemoveList = [];
matTemp = mat;

for i in 1:4  # Suppose 4 columns need to be removed

    # 1. find the index of the column with the largest column sum at current iteration
    sumTemp = sum(matTemp, dims=1);
    maxSumTemp = maximum(sumTemp);
    idxColRemoveTemp = argmax(sumTemp)[2];
    
    # 2. record the orignial index of the removed scenario
    idxColRemoveOrig = findall(x->x==maxSumTemp, matColSum)[1][2];
    push!(idxColRemoveList, idxColRemoveOrig);
    
    # 3. update the matrix. Note that the corresponding row is also removed.
    matTemp = matTemp[Not(idxColRemoveTemp), Not(idxColRemoveTemp)];

end

Tags: oftheforcolumn矩阵matrixsummat
2条回答

python解决方案:

import numpy as np

mat = np.random.rand(5, 5)
n_remove = 3

original = np.arange(len(mat)).tolist()
removed = []

for i in range(n_remove):
    col_sum = np.sum(mat, axis=0)
    col_rm = np.argsort(col_sum)[-1]
    removed.append(original.pop(col_rm))
    mat = np.delete(np.delete(mat, col_rm, 0), col_rm, 1)

print(removed)
print(original)
print(mat)

我猜您遇到的问题是跟踪原始数组中当前列/行的索引。我刚刚使用了一个列表[0, 1, 2, ...],然后在每次迭代中弹出一个值

对问题进行编码的一种更简单的方法是用非常小的数字替换所选列中的元素,而不是删除该列。这种方法避免了使用“sort”和“pop”来提高代码效率

import numpy as np

n = 1000
mat = np.random.rand(n, n)
n_remove = 500
removed = []

for i in range(n_remove):
    # get sum of each column
    col_sum = np.sum(mat, axis=0)
    col_rm = np.argmax(col_sum)
    # record the column ID
    removed.append(col_rm)
    
    # replace elements in the col_rm-th column and row with the zeros
    mat[:, col_rm] = 1e-10
    mat[col_rm, :] = 1e-10  
   
print(removed)

相关问题 更多 >

    热门问题