Using a for
loop, how would I write code to generate an array of indices where at each iteration k
of the loop, I would generate an array of indices from [1, 2, 3, ... N]
that excludes k
from the set?
As an example, if I had k = 3
iterations, the first iteration would give me indices (2,3)
, the second iteration would give me indices (1,3)
and finally the third iteration would give me indices (1,2)
.
You can use setdiff
at each iteration to exclude the current iteration ID, like so -
for iteration_id = 1:3
indices = setdiff(1:3,iteration_id)
end
Code run -
indices =
2 3
indices =
1 3
indices =
1 2
You can employ a vectorized approach to generate all indices in one go, which could be easily used inside the loop(s) if you have to use those indices -
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,[])'
Code run -
valid_indices =
2 3
1 3
1 2
Another very simple way to do this:
N=3;
for k=1:N
[1:k-1,k+1:N]
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With