使用 for
循环,我将如何编写代码来生成索引数组,在循环的每次迭代 k
中,我会生成一个索引数组[1, 2, 3, ... N]
从集合中排除 k
?
例如,如果我有 k = 3
次迭代,第一次迭代会给我索引 (2,3)
,第二次迭代会给我索引 (1,3)
最后第三次迭代会给我索引 (1,2)
。
最佳答案
方法#1
您可以使用 setdiff
在每次迭代中排除当前迭代 ID,就像这样 -
for iteration_id = 1:3
indices = setdiff(1:3,iteration_id)
end
代码运行-
indices =
2 3
indices =
1 3
indices =
1 2
方法#2(矢量化)
您可以采用矢量化方法一次性生成所有索引,如果您必须使用这些索引,可以很容易地在循环内使用 -
num_iters = 3; %// Number of iterations
all_indices = repmat([1:num_iters]',1,num_iters) %//'
all_indices(1:num_iters+1:end)=[]
valid_indices = reshape(all_indices,num_iters-1,[])'
代码运行-
valid_indices =
2 3
1 3
1 2
关于matlab - 通过在每次迭代中省略一个索引来生成一组索引的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28025629/