跟踪最佳索引,同时每次迭代将矩阵减少 1x1



>SETUP

我有一个 NxN 对角矩阵,我在每次迭代中将矩阵缩小 1x1。

indices = np.arange(0, np.size(n_n_matrix, 0)).tolist()
for iter in range(0, N-K)
opt_indices = criterion(n_n_matrix)
lost_index = [i for i in indices if i not in opt_indices][0]
n_n_matrix = np.delete(traj_dist_matrix, lost_index, axis=0)
n_n_matrix = np.delete(traj_dist_matrix, lost_index, axis=1)

我这样做,直到我有一个 KxK 对角矩阵。 如何根据未删除的索引在原始 NxN 矩阵中的位置来跟踪它们?

失败

我尝试失败了:

lost_indices = [], list_indices_iter = []
>>>loop above<<<
count_1 = sum(lost_index >= idx for idx in lost_indices_iter)
count_2 = sum(lost_index + count_1 >= idx for idx in lost_indices_iter) - count_1
...
lost_indices.append(lost_index + count_1 + count_2 ...)
lost_indices_iter.append(lost_index)
left_opt_indices = [i for i in indices if i not in lost_indices]

缩小问题范围

我的问题由以下示例说明:如果我删除索引i,下一个矩阵会缩小。如果我在下一次迭代中删除索引j>=i,我需要将1添加到j,因为它的位置与原始 NxN 矩阵相比有所下降。如果我随后删除索引k=>j,我需要考虑前面的两个更改,依此类推。

更新:我的一个朋友给了我一个提示。它是两行的。

tracker_original_indices = np.arange(0, np.size(traj_dist_matrix, 0))
tracker_original_indices = np.delete(tracker_original_indices, lost_index, axis=0)

也许不是最好的方法,但我会跟踪字典,其中键是原始索引位置,值是当前索引位置。我称之为index_mapping

我创建了一个函数来将删除应用于index_mapping,并显示您可以创建一个删除列表并在最后应用它们,但您也可以逐个应用它们

每个删除事件都位于 x 或 y 位置以及当前数组的索引中

def process_deletions(index_mapping, deletions):
for deletion in deletions:
del_kind = deletion['kind']
del_ind = deletion['index']
for orig_ind,curr_ind in index_mapping[del_kind].items():
#Don't update an index if it's less than the one deleted
if curr_ind < del_ind:
continue
#Set the deleted index to now be -1
elif curr_ind == del_ind:
index_mapping[del_kind][orig_ind] = -1
#Otherwise if the index is greater than the one deleted
#decrement the new index it points to
#i.e. if index 3 is deleted, what was index 5 is now index 4
else:
index_mapping[del_kind][orig_ind] -= 1
return index_mapping

num_rows = 10
num_cols = 10
#Start out that each original index points to it's same position in the unmodified matrix
index_mapping = {
'x':{i:i for i in range(num_rows)},
'y':{i:i for i in range(num_cols)},
}
#Keep track of all the deletions made
#Can alternatively make one deletion at a time and keep applying it to the index_mapping
deletions = [
{'kind':'x', 'index':1},
{'kind':'y', 'index':1},
{'kind':'x', 'index':6},
{'kind':'y', 'index':6},
{'kind':'x', 'index':4},
{'kind':'y', 'index':4},
]
index_mapping = process_deletions(index_mapping, deletions)
print(index_mapping)

最新更新