0
votes

Suppose the input is the following matrix,

[0,1,0,1;
 1,0,1,0]

Then, the expected output would be (1,2,1), (1,2,3) (1,4,1), (1,4,3), (2,1,2) (2,1,4), (2,3,2), (2,3,4) The reason is that: in the first row, there are four ordered (1,0) pairs, whose indices are (2,1), (2,3), (4,1) and (4,3).. Similarly, in the second row, there are four ordered (1,0) pairs, whose indices are (1,2), (1,4), (3,2) and (3,4). I now how to code this in matlab row by row.

>> a=[ 0,1,0,1; 1,0,1,0]

a =

     0     1     0     1
     1     0     1     0

>> b=a(1,:);
>> b

b =

     0     1     0     1

>> x1=find(b==1)

x1 =

     2     4

>> x0=find(b==0)

x0 =

     1     3

>> [X,Y]=meshgrid(x1,x0);
>> c=[X(:),Y(:)]

c =

     2     1
     2     3
     4     1
     4     3

>> d=[ repmat(1, [4,1])  c  ]

d =

     1     2     1
     1     2     3
     1     4     1
     1     4     3

With for loop, this can be solved. My question is: do you think you can code this in matlab without for loops? Many thaks for your time and attention.

1

1 Answers

0
votes

You can do this with some clever use of meshgrid.

a = [0,1,0,1;1,0,1,0];
[r0, c0] = ind2sub(size(a), find(a == 0)); % row and column of every 0
[r1, c1] = ind2sub(size(a), find(a == 1)); % row and column of every 1
[R0, R1] = meshgrid(r0, r1);
[C0, C1] = meshgrid(c0, c1);
idx = (R0 == R1); % consider only entries whose rows match
list = [R0(idx), C1(idx), C0(idx)]

Output:

list =

     1     2     1
     1     4     1
     2     1     2
     2     3     2
     1     2     3
     1     4     3
     2     1     4
     2     3     4