Search code examples
postgresqlpostgispgadmin

cross product of two vectors(rows) in postgresql


I tried to calculate cross product of two vectors in postgresql. illustrations: input:

edgex edgey edgez
6.80837996699847 39.4163159399759 0
0 0 12

cross product these two rows(vectors) in postgresql by using query


Solution

  • Create a function for it. Assuming these are 3D point PostGIS geometries:

    CREATE OR REPLACE FUNCTION ST_CrossProduct(point_a geometry, point_b geometry)
      RETURNS geometry AS
    $BODY$SELECT ST_SetSRID(ST_MakePoint(
      a2 * b3 - a3 * b2,
      a3 * b1 - a1 * b3,
      a1 * b2 - a2 * b1), ST_SRID($1))
    FROM (SELECT
      ST_X($1) AS a1, ST_Y($1) AS a2, COALESCE(ST_Z($1), 0.0) AS a3,
      ST_X($2) AS b1, ST_Y($2) AS b2, COALESCE(ST_Z($2), 0.0) AS b3
    ) AS f$BODY$
    LANGUAGE sql IMMUTABLE;
    

    Use it:

    SELECT ST_AsText(ST_CrossProduct(
         ST_MakePoint(6.80837996699847, 39.4163159399759, 0),
         ST_MakePoint(0, 0, 12)));
    
                       st_astext                    
    ------------------------------------------------
     POINT Z (472.995791279711 -81.7005596039816 0)
    (1 row)