diff scripts/linear-algebra/cross.m @ 3883:69b6bd271277

[project @ 2002-04-02 21:05:10 by jwe]
author jwe
date Tue, 02 Apr 2002 21:05:10 +0000
parents f8dde1807dee
children 38c61cbf086c
line wrap: on
line diff
--- a/scripts/linear-algebra/cross.m
+++ b/scripts/linear-algebra/cross.m
@@ -19,40 +19,53 @@
 ## Computes the vector cross product of the two 3-dimensional vectors
 ## @var{x} and @var{y}.
 ##
-## A row vector is returned if @var{x} and @var{y} are both row vectors;
-## otherwise, a column vector is returned.
-##
 ## @example
 ## @group
 ## cross ([1,1,0], [0,1,1])
 ##      @result{} [ 1; -1; 1 ]
 ## @end group
 ## @end example
+##
+## If @var{x} and @var{y} are two - dimensional matrices the
+## cross product is applied along the first dimension with 3 elements.
+##
 ## @end deftypefn
 
-## Author: KH <Kurt.Hornik@ci.tuwien.ac.at>
+## Author: Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>
 ## Created: 15 October 1994
 ## Adapted-By: jwe
 
 function z = cross (x, y)
-
+	
   if (nargin != 2)
     usage ("cross (x, y)");
   endif
 
-  if (length (x) == 3 && length (y) == 3)
-
-    z = [x(2)*y(3) - x(3)*y(2); x(3)*y(1) - x(1)*y(3); x(1)*y(2) - x(2)*y(1)];
-
-    x_nr = rows (x);
-    y_nr = rows (y);
+  ## XXX COMPATIBILITY XXX opposite behaviour for cross(row,col)
+  ## Swap x and y in the assignments below to get the matlab behaviour.
+  ## Better yet, fix the calling code so that it uses conformant vectors.
+  if (columns(x) == 1 && rows(y) == 1)
+    warning ("cross: taking cross product of column by row");
+    y = y.';
+  elseif (rows(x) == 1 && columns(y) == 1)
+    warning ("cross: taking cross product of row by column");
+    x = x.';
+  endif
 
-    if (x_nr == y_nr && x_nr == 1)
-      z = z.';
+  if (size(x) == size(y))
+    if (rows(x) == 3)
+      z = [ ( x (2,:) .* y (3,:) - x (3,:) .* y (2,:) ) ;
+            ( x (3,:) .* y (1,:) - x (1,:) .* y (3,:) ) ;
+            ( x (1,:) .* y (2,:) - x (2,:) .* y (1,:) ) ];
+    elseif (columns(x) == 3)
+      z = [ ( x (:,2) .* y (:,3) - x (:,3) .* y (:,2) ) , \
+            ( x (:,3) .* y (:,1) - x (:,1) .* y (:,3) ) , \
+            ( x (:,1) .* y (:,2) - x (:,2) .* y (:,1) ) ];
+    else
+      error ("cross: x,y must have dimension nx3 or 3xn");
     endif
-
   else
-    error ("cross: both x and y must be 3-dimensional vectors");
+    error ("cross: x and y must have the same dimensions");
   endif
 
 endfunction