Loop, which generates an array of indices, omitting one index per iteration

Using the for loop, how would I write code to generate an array of indices, where on each iteration of the k loop I would generate an array of indices from [1, 2, 3, ... N] , which excludes k from being installed?

As an example, if I had iterations k = 3 , 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) .

+5
source share
5 answers

another way for any n

  n = 3; [ii, ~] = find( ~eye(n) ); indices = reshape( ii, n-1, [] ).' 
+4
source

Approach No. 1

You can use setdiff at each iteration to exclude the current iteration id, for example:

 for iteration_id = 1:3 indices = setdiff(1:3,iteration_id) end 

Code Execution -

 indices = 2 3 indices = 1 3 indices = 1 2 

Approach No. 2 (vector image)

You can use a vectorized approach to generate all indices at once, which can be easily used inside the loop (s) if you need to use these 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 Execution -

 valid_indices = 2 3 1 3 1 2 
+7
source

Another very easy way to do this:

 N=3; for k=1:N [1:k-1,k+1:N] end 
+6
source

Use

 all_indices = [1 2 3]; %// these can be arbitrary numbers, not necessarily 1:N N = numel(all_indices); for n = 1:N selected_indices = all_indices([1:n-1 n+1:N]); end 

If you want to generate everything at once, as rows of one matrix, you can use nchoosek :

 all_indices = [1 2 3]; %// again, these can be arbitrary numbers selected_indices = nchoosek(all_indices, numel(all_indices)-1); %// generate combinations selected_indices = flipud(selected_indices); %// put results in the intended order 

In the example, this gives

 selected_indices = 2 3 1 3 1 2 
+4
source

If you don't need to arrange the columns, you can simply:

 n = 5; indices = reshape(ones(n-1,1)*(n:-1:1),n,[]); 

Not entirely self-evident, but it abuses the structure of the indices matrix.

 indices = 5 4 3 2 5 4 3 1 5 4 2 1 5 3 2 1 4 3 2 1 
+2
source

Source: https://habr.com/ru/post/1211411/


All Articles