Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop that generates an array of indices by omitting one index at each iteration

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).

like image 216
Amira Akra Avatar asked Jan 19 '15 13:01

Amira Akra


2 Answers

Approach #1

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

Approach #2 (Vectorized)

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
like image 163
Divakar Avatar answered Sep 29 '22 10:09

Divakar


Another very simple way to do this:

N=3;
for k=1:N
    [1:k-1,k+1:N]
end
like image 38
Dennis Jaheruddin Avatar answered Sep 29 '22 09:09

Dennis Jaheruddin