Fortran - Logical Indexing
<p>Suppose I have a matrix <code>A</code> which is <code>(m x n)</code> and a vector <code>B</code> which is <code>(m x 1)</code>. This vector <code>B</code> is a vector of zeros and ones. </p>

<p>Also let the scalar <code>s</code> be the sum of the elements in <code>B</code> .</p>

<p>I want to create a matrix <code>C</code> which is <code>s x n</code> corresponding to the rows of <code>B</code> which equal 1, and a vector <code>D</code> which is s x 1, with the position of those elements in <code>A</code>.</p>

<pre><code>Take as an example: 

      A = [1, 2, 3; 
           4, 5, 6; 
           7, 8, 9; 
           10, 11, 12; 
           13, 14, 15 ]

        B = [0; 1; 0; 1; 1]

    Then:
C = [ 4, 5, 6; 
     10, 11, 12; 
     13, 14, 15 ]
and
D = [2; 
     4
     5]
</code></pre>

<p>As of now my fortran code looks like:</p>

<pre><code>PROGRAM test1
IMPLICIT NONE

 REAL, DIMENSION(5,3) :: A
INTEGER, DIMENSION(5,1) :: B = 0
INTEGER :: i, j, k

k = 1

!Create A matrix
do i=1,5
    do j=1,3
        A(i,j) = k
        k = k+1
    end do
end do

!Create B matrix
B(2,1) = 1
B(4,1) = 1
B(5,1) = 1


end program
</code></pre>

<p>In matlab I could create C simply by making: C = A(logical(B),:), and D in a similar way.</p>

<p>How can I do it in fortran, avoiding loops? I have looked into the <code>where</code> and <code>forall</code> statements, but they are not exactly what I am looking for. </p>