Search code examples
matlabloopscontrolsindices

Simplify the looping under two sets of conditions


I want to establish a pair of indices =[row col] where

row = 4 * (n-1) + i and col = 4 * (m-1) + i

Explanation for i, m and n:

For n = 1 and m = 2, 3, 4, loop i = 1 : 4.

For n = 2 and m = 1, loop i = 1 : 4.

For n = 3 and m = 5, loop i = 1 : 4.

The outcome should be:

row = [1 1 1 2 2 2 3 3 3 4 4 4 5 6 7 8 9 10 11 12]

col = [5 9 13 6 10 14 7 11 15 8 12 16 1 2 3 4 17 18 19 20]

That is, I want to establish pairs of indices under different sets of n-m conditions.


My trial:

row = []; col = [];
n = 1;
for i = 1 : 4
   for m = [2 3 4]
      row = [row 4 * (n - 1) + i];
      col = [col 4 * (m - 1) + i];
   end
end

n = 2; m = 1;
for i = 1 : 4
   row = [row 4 * (n - 1) + i];
   col = [col 4 * (m - 1) + i];
end

n= 3; m = 5;
for i = 1 : 4
   row = [row 4 * (n - 1) + i];
   col = [col 4 * (m - 1) + i];
end

This works but indeed I have many n-m conditions and the looping for i = 1 : 4 appeared repeatedly which seems that can be simplified.

May I know if there are any elegant solutions to finish my objective?

I appreciate for your help.


Solution

  • You can use a bsxfun based solution for all those three cases -

    ii = 1:4
    row = reshape(bsxfun(@(A,B) 4 * (B-1) + A,ii,n'),1,[])  %//'
    col = reshape(bsxfun(@(A,B) 4 * (B-1) + A,ii,m'),1,[])  %//'
    

    The inputs would be as listed next.

    Case #1:

    m = [2, 3, 4]
    n = ones(1,numel(m))
    

    Case #2:

    n = 2
    m = 1
    

    Case #3:

    n = 3
    m = 5