title: Computing the cross product of two vectors in Fortran 90
body: <p>I would like to compute the cross product of two vectors in Fortran 90.  For example, in words, the cross product of (1, 2, 3) and (4, 5, 6) turns out to be (-3, 6, -3) in Cartesian coordinates.  I wrote the following code (main program followed by function definition):</p>
  
  <pre><code>PROGRAM crosstest
    IMPLICIT NONE
  
    INTEGER, DIMENSION(3) :: m, n
    INTEGER, DIMENSION(3) :: cross
    INTEGER, DIMENSION(3) :: r
  
    m=(/1, 2, 3/)
    n=(/4, 5, 6/)
    r=cross(m,n)
  
  END PROGRAM crosstest
  
  FUNCTION cross(a, b)
    INTEGER, DIMENSION(3) :: cross
    INTEGER, DIMENSION(3), INTENT(IN) :: a, b
  
    cross(1) = a(2) * b(3) - a(3) * b(2)
    cross(2) = a(3) * b(1) - a(1) * b(3)
    cross(3) = a(1) * b(2) - a(2) * b(1)
  END FUNCTION cross
  </code></pre>
  
  <p>But, I get an error message: </p>
  
  <pre><code>crosstest.f90:10.9:
  
    r=cross(m,n)
           1
  Error: Rank mismatch in array reference at (1) (2/1)
  </code></pre>
  
  <p>where line 10 is <code>r=cross(m,n)</code>.  It seems that I must be specifying a dimension incorrectly.  Here are a few ideas I have: </p>
  
  <ol>
  <li><p>Perhaps the declaration of the function <code>cross</code> in the main program should be simply an integer variable, rather than a 1by3 integer array.  So I tried deleting the <code>, DIMENSION(3)</code> in the <code>INTEGER, DIMENSION(3) :: cross</code> line in the main program.  But I get an error message:</p>
  
  <pre><code>crosstest.f90:10.4:
  
    r=cross(m,n)
      1
  Error: The reference to function 'cross' at (1) either needs an
  explicit INTERFACE or the rank is incorrect
  </code></pre>
  
  <p>so this is even worse, probably.</p></li>
  <li><p>Some (but not all) Fortran function examples on the web place an <code>EXTERNAL</code> statement after the function declaration in the main program.  So I tried placing a line <code>EXTERNAL cross</code> after the declaration block in the main program.  I get an error message:</p>
  
  <pre><code>crosstest.f90:8.16:
  
    EXTERNAL cross
                  1
  Error: EXTERNAL attribute conflicts with DIMENSION attribute at (1)
  </code></pre>
  
  <p>So this seems incorrect also.</p></li>
  <li><p>Some (but not all) Fortran function examples on the web place a <code>RETURN</code> statement on the second-to-last line of the function definition.  I tried this, but I get the original rank mismatch error:</p>
  
  <pre><code>crosstest.f90:10.9:
  
    r=cross(m,n)
           1
  Error: Rank mismatch in array reference at (1) (2/1)
  </code></pre>
  
  <p>So this does not fix the problem.</p></li>
  </ol>
  
  <p>Can you please help me see my error?  </p>