1 ## Copyright (C) 1995-2012 Kurt Hornik
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} cross (@var{x}, @var{y})
21 ## @deftypefnx {Function File} {} cross (@var{x}, @var{y}, @var{dim})
22 ## Compute the vector cross product of two 3-dimensional vectors
23 ## @var{x} and @var{y}.
27 ## cross ([1,1,0], [0,1,1])
28 ## @result{} [ 1; -1; 1 ]
32 ## If @var{x} and @var{y} are matrices, the cross product is applied
33 ## along the first dimension with 3 elements. The optional argument
34 ## @var{dim} forces the cross product to be calculated along
35 ## the specified dimension.
36 ## @seealso{dot, curl, divergence}
39 ## Author: Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
40 ## Created: 15 October 1994
43 function z = cross (x, y, dim)
45 if (nargin != 2 && nargin != 3)
49 if (ndims (x) < 3 && ndims (y) < 3 && nargin < 3)
50 ## COMPATIBILITY -- opposite behaviour for cross(row,col)
51 ## Swap x and y in the assignments below to get the matlab behaviour.
52 ## Better yet, fix the calling code so that it uses conformant vectors.
53 if (columns (x) == 1 && rows (y) == 1)
54 warning ("cross: taking cross product of column by row");
56 elseif (rows (x) == 1 && columns (y) == 1)
57 warning ("cross: taking cross product of row by column");
63 dim = find (size (x) == 3, 1);
65 error ("cross: must have at least one dimension with 3 elements");
68 if (size (x, dim) != 3)
69 error ("cross: dimension DIM must have 3 elements");
75 idx2 = idx3 = idx1 = {':'}(ones (1, nd));
80 if (size_equal (x, y))
87 z = cat (dim, (x2.*y3 - x3.*y2), (x3.*y1 - x1.*y3), (x1.*y2 - x2.*y1));
89 error ("cross: X and Y must have the same dimensions");
98 %! assert(cross(x, y), r, 2e-8);
103 %! r = [(2*6-3*5) (3*4-1*6) (1*5-2*4)];
104 %! assert(cross(x, y), r, 2e-8);
107 %! x = [1 0 0; 0 1 0; 0 0 1];
108 %! y = [0 1 0; 0 0 1; 1 0 0];
109 %! r = [0 0 1; 1 0 0; 0 1 0];
110 %! assert(cross(x, y, 2), r, 2e-8);
111 %! assert(cross(x, y, 1), -r, 2e-8);