3d Vector Types and operators
3d Vector Types and operators
От:
Andrew Bailey <hazlorealidad@gmail.com>
Дата:
Hi,
I cant find in the documentation support for a 3 dimensional vector,
I have only seen the array type, I am interested in doing vector dot
products and vector cross products, also summing vectors and
multiplying by a scalar quantity
select array[1,2,3]+array[2,4,5];
select 2*array[1,2,3];
The error message is:
No operator matches the given name and argument type(s). You might
need to add explicit type casts.
Has anyone tried to do this before?
Has anyone written operators for this?
I have got as far as
CREATE or replace FUNCTION add(anyarray, anyarray) RETURNS anyarray
AS 'select array[$1[1] + $2[1],$1[2] + $2[2],$1[3] + $2[3]];'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
drop FUNCTION dot(anyarray, anyarray);
CREATE or replace FUNCTION dot(anyarray, anyarray) RETURNS int
AS 'select $1[1] * $2[1]+$1[2] * $2[2]+$1[3] * $2[3];'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
It works for integer arrays:
select add(array[1,2,3],array[2,4,5]);
add
---------
{3,6,8}
(1 row)
select dot(array[1,2,3],array[2,4,5]);
dot
-----
25
but it gives me an error for a floating point array
epm=# select add(array[1.2,2,3],array[2,4,5]);
ERROR: function add(numeric[], integer[]) does not exist
LINE 1: select add(array[1.2,2,3],array[2,4,5]);
^
HINT: No function matches the given name and argument types. You
might need to add explicit type casts.
How can I fix it to cope with real or integer arrays?
How could I change this to use operators?
Is it efficient? Can it be made more efficient?
Thanks in advance
Andy Bailey
Re: 3d Vector Types and operators
От:
Sam Mason <sam@samason.me.uk>
Дата:
On Wed, Oct 14, 2009 at 12:04:26PM -0500, Andrew Bailey wrote:
> I cant find in the documentation support for a 3 dimensional vector,
> I have only seen the array type, I am interested in doing vector dot
> products and vector cross products, also summing vectors and
> multiplying by a scalar quantity
If you did do this, I'd be tempted to use something like:
create type point3d AS (
x float8, y float8, z float8
);
and then write your functions using this. The length of an array isn't
part of its type and so PG wouldn't be able to stop you from writing:
select array[1,2,3] + array[2,3,4,5,6];
if you provided the appropriate operators. If you use a fixed sized
tuple, as above, you'd get errors if you tried to use points of the
wrong dimensionality.
--
Sam http://samason.me.uk/