我希望在删除前一列的最大和之后,在每次迭代中检索该列的原始索引。同时,在每次迭代时,也会从矩阵中删除已删除列的同一索引行
例如,在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
python解决方案:
我猜您遇到的问题是跟踪原始数组中当前列/行的索引。我刚刚使用了一个列表
[0, 1, 2, ...]
,然后在每次迭代中弹出一个值对问题进行编码的一种更简单的方法是用非常小的数字替换所选列中的元素,而不是删除该列。这种方法避免了使用“sort”和“pop”来提高代码效率
相关问题 更多 >
编程相关推荐