Provides mathematical vector operations for various vector types, inspired by libraries like Processing and openFrameworks.
Supported vector representations include:
Vec2
(2D), Vec3
(3D), Vec4
(4D), and ArrayVec
(N-dimensional wrapper around double[]
).double
arrays ([D
).[]
) and sequences (ISeq
).Most operations are defined via the [[VectorProto]] protocol, which is extended for all supported types.
These vector types also implement standard Clojure/Java protocols like Seqable
, Indexed
, IFn
, Counted
, Associative
, IReduce
, ILookup
, etc., enabling them to be used flexibly as sequences, arrays, or functions.
Provides mathematical vector operations for various vector types, inspired by libraries like Processing and openFrameworks. Supported vector representations include: * **Fixed-size custom types**: `Vec2` (2D), `Vec3` (3D), `Vec4` (4D), and `ArrayVec` (N-dimensional wrapper around `double[]`). * **Built-in array type**: `double` arrays (`[D`). * **Variable-size Clojure collections**: persistent vectors (`[]`) and sequences (`ISeq`). * **Numbers**: Treated as 1D vectors. Most operations are defined via the [[VectorProto]] protocol, which is extended for all supported types. These vector types also implement standard Clojure/Java protocols like `Seqable`, `Indexed`, `IFn`, `Counted`, `Associative`, `IReduce`, `ILookup`, etc., enabling them to be used flexibly as sequences, arrays, or functions.
(abs v)
Absolute value of vector elements
Absolute value of vector elements
(acos vector)
Applies acos to vector elements.
Applies acos to vector elements.
(acosh vector)
Applies acosh to vector elements.
Applies acosh to vector elements.
(acot vector)
Applies acot to vector elements.
Applies acot to vector elements.
(acoth vector)
Applies acoth to vector elements.
Applies acoth to vector elements.
(acsc vector)
Applies acsc to vector elements.
Applies acsc to vector elements.
(acsch vector)
Applies acsch to vector elements.
Applies acsch to vector elements.
(aligned? v1 v2)
(aligned? v1 v2 tol)
Checks if two vectors are aligned, meaning they point in approximately the same direction.
This is determined by checking if the angle between them (calculated using angle-between
)
is less than the specified tolerance
.
Defaults to an absolute tolerance of 1.0e-6
.
Checks if two vectors are aligned, meaning they point in approximately the same direction. This is determined by checking if the angle between them (calculated using [[angle-between]]) is less than the specified `tolerance`. Defaults to an absolute tolerance of `1.0e-6`.
(angle-between v1 v2)
Returns the angle between two vectors in radians.
The angle is always positive and lies between 0 and π. Returns 0 if either vector is zero.
Returns the angle between two vectors in radians. The angle is always positive and lies between 0 and π. Returns 0 if either vector is zero.
(approx v)
(approx v d)
Rounds to d
(default: 2) decimal places
Rounds to `d` (default: 2) decimal places
(array->vec2 arr)
Converts doubles array to Vec2
Converts doubles array to Vec2
(array->vec3 arr)
Converts doubles array to Vec3
Converts doubles array to Vec3
(array->vec4 arr)
Converts doubles array to Vec4
Converts doubles array to Vec4
(array-vec xs)
Creates ArrayVec type based on provided sequence xs
.
Creates ArrayVec type based on provided sequence `xs`.
(as-vec v)
(as-vec v xs)
Creates vector from sequence as given type. If there is no sequence fill with 0.0
.
Creates vector from sequence as given type. If there is no sequence fill with `0.0`.
(asec vector)
Applies asec to vector elements.
Applies asec to vector elements.
(asech vector)
Applies asech to vector elements.
Applies asech to vector elements.
(asin vector)
Applies asin to vector elements.
Applies asin to vector elements.
(asinh vector)
Applies asinh to vector elements.
Applies asinh to vector elements.
(atan vector)
Applies atan to vector elements.
Applies atan to vector elements.
(atanh vector)
Applies atanh to vector elements.
Applies atanh to vector elements.
(average v)
(average v weights)
Mean or weighted average of the vector
Mean or weighted average of the vector
(average-vectors vs)
(average-vectors init vs)
Average / centroid of vectors. Input: initial vector (optional), list of vectors
Average / centroid of vectors. Input: initial vector (optional), list of vectors
(axis-rotate v angle axis)
(axis-rotate v angle axis pivot)
Rotates vector. Only for Vec3
types
Rotates vector. Only for `Vec3` types
(base-from v)
List of perpendicular vectors (basis). Works only for Vec2
and Vec3
types.
List of perpendicular vectors (basis). Works only for `Vec2` and `Vec3` types.
(cbrt vector)
Applies cbrt to vector elements.
Applies cbrt to vector elements.
(ceil vector)
Applies ceil to vector elements.
Applies ceil to vector elements.
(clamp v)
(clamp v mn mx)
Clamps the elements of vector v
element-wise between a minimum (mn
) and maximum (mx
) value.
In the single-arity version [v]
, elements are clamped between 0.0 and Double/MAX_VALUE
.
Clamps the elements of vector `v` element-wise between a minimum (`mn`) and maximum (`mx`) value. In the single-arity version `[v]`, elements are clamped between 0.0 and `Double/MAX_VALUE`.
(cos vector)
Applies cos to vector elements.
Applies cos to vector elements.
(cosh vector)
Applies cosh to vector elements.
Applies cosh to vector elements.
(cot vector)
Applies cot to vector elements.
Applies cot to vector elements.
(coth vector)
Applies coth to vector elements.
Applies coth to vector elements.
(csc vector)
Applies csc to vector elements.
Applies csc to vector elements.
(csch vector)
Applies csch to vector elements.
Applies csch to vector elements.
(degrees vector)
Applies degrees to vector elements.
Applies degrees to vector elements.
(delta-eq v1 v2)
(delta-eq v1 v2 abs-tol)
(delta-eq v1 v2 abs-tol rel-tol)
Equality with given absolute (and/or relative) toleance.
Equality with given absolute (and/or relative) toleance.
(differences v)
(differences v diffs)
(differences v diffs lag)
Computes the lagged differences of a vector or sequence.
This function calculates the difference between elements separated by a fixed distance (lag
)
and can apply this operation diffs
times.
It supports multiple arities:
[v]
: Computes the 1st difference with lag 1 (default: diffs=1
, lag=1
).[v diffs]
: Computes the diffs
-th difference with lag 1 (default: lag=1
).[v diffs lag]
: Computes the diffs
-th difference with the specified lag
.Returns a sequence of the computed differences.
Computes the lagged differences of a vector or sequence. This function calculates the difference between elements separated by a fixed distance (`lag`) and can apply this operation `diffs` times. It supports multiple arities: - `[v]`: Computes the 1st difference with lag 1 (default: `diffs=1`, `lag=1`). - `[v diffs]`: Computes the `diffs`-th difference with lag 1 (default: `lag=1`). - `[v diffs lag]`: Computes the `diffs`-th difference with the specified `lag`. Returns a sequence of the computed differences.
(dist v1 v2)
Euclidean distance between vectors
Euclidean distance between vectors
(dist-abs v1 v2)
Manhattan distance between vectors
Manhattan distance between vectors
(dist-cheb v1 v2)
Chebyshev distance between 2d vectors
Chebyshev distance between 2d vectors
(dist-discrete v1 v2)
(dist-discrete v1 v2 eps)
Computes the discrete distance between two vectors v1
and v2
.
This is the number of positions where the corresponding elements are considered different.
With an optional absolute tolerance eps
, elements at index i
are considered different if |v1_i - v2_i| > eps
.
Returns the count of differing elements.
Computes the discrete distance between two vectors `v1` and `v2`. This is the number of positions where the corresponding elements are considered different. With an optional absolute tolerance `eps`, elements at index `i` are considered different if `|v1_i - v2_i| > eps`. Returns the count of differing elements.
(dist-sq v1 v2)
Squared Euclidean distance between vectors
Squared Euclidean distance between vectors
(div v1)
(div v1 v)
Vector division or reciprocal.
Vector division or reciprocal.
(edelta-eq v1 v2)
(edelta-eq v1 v2 abs-tol)
(edelta-eq v1 v2 abs-tol rel-tol)
Element-wise equality with given absolute (and/or relative) toleance.
Element-wise equality with given absolute (and/or relative) toleance.
(ediv v1 v2)
Element-wise division of two vectors.
Element-wise division of two vectors.
(einterpolate v1 v2 v)
(einterpolate v1 v2 v f)
Interpolates vector selement-wise, optionally set interpolation fn (default: lerp)
Interpolates vector selement-wise, optionally set interpolation fn (default: lerp)
(emn v1 v2)
Element-wise min from two vectors.
Element-wise min from two vectors.
(emult v1)
(emult v1 v2)
Element-wise vector multiplication (Hadamard product).
Element-wise vector multiplication (Hadamard product).
(emx v1 v2)
Element-wise max from two vectors.
Element-wise max from two vectors.
(exp vector)
Applies exp to vector elements.
Applies exp to vector elements.
(expm1 vector)
Applies expm1 to vector elements.
Applies expm1 to vector elements.
(faceforward n v)
Flips vector n
if dot(n, v)
is negative. Returns n
if dot(n, v)
is non-negative. Useful for ensuring consistent vector orientation, such as making a normal vector face towards a reference vector v
.
Flips vector `n` if `dot(n, v)` is negative. Returns `n` if `dot(n, v)` is non-negative. Useful for ensuring consistent vector orientation, such as making a normal vector face towards a reference vector `v`.
(floor vector)
Applies floor to vector elements.
Applies floor to vector elements.
(fmap v f)
Applies function to all vector values (like map but returns the same type).
Applies function to all vector values (like map but returns the same type).
(frac vector)
Applies frac to vector elements.
Applies frac to vector elements.
(from-polar v)
From polar coordinates (2d, 3d only)
From polar coordinates (2d, 3d only)
(generate-vec2 f)
(generate-vec2 f1 f2)
Generates Vec2 with fn(s)
Generates Vec2 with fn(s)
(generate-vec3 f)
(generate-vec3 f1 f2 f3)
Generates Vec3 with fn(s)
Generates Vec3 with fn(s)
(generate-vec4 f)
(generate-vec4 f1 f2 f3 f4)
Generates Vec4 with fn(s)
Generates Vec4 with fn(s)
(heading v)
Angle between vector and unit vector [1,0,...]
Angle between vector and unit vector `[1,0,...]`
(interpolate v1 v2 t)
(interpolate v1 v2 t f)
Interpolates vectors, optionally set interpolation fn (default: lerp)
Interpolates vectors, optionally set interpolation fn (default: lerp)
(is-near-zero? v)
(is-near-zero? v abs-tol)
(is-near-zero? v abs-tol rel-tol)
Equality to zero 0
with given absolute (and/or relative) toleance.
Equality to zero `0` with given absolute (and/or relative) toleance.
(lerp v1 v2 t)
Linear interpolation of vectors
Linear interpolation of vectors
(limit v len)
Limits length of the vector by given value
Limits length of the vector by given value
(log vector)
Applies log to vector elements.
Applies log to vector elements.
(log10 vector)
Applies log10 to vector elements.
Applies log10 to vector elements.
(log1mexp vector)
Applies log1mexp to vector elements.
Applies log1mexp to vector elements.
(log1p vector)
Applies log1p to vector elements.
Applies log1p to vector elements.
(log1pexp vector)
Applies log1pexp to vector elements.
Applies log1pexp to vector elements.
(log1pmx vector)
Applies log1pmx to vector elements.
Applies log1pmx to vector elements.
(log1psq vector)
Applies log1psq to vector elements.
Applies log1psq to vector elements.
(log2 vector)
Applies log2 to vector elements.
Applies log2 to vector elements.
(logexpm1 vector)
Applies logexpm1 to vector elements.
Applies logexpm1 to vector elements.
(logit vector)
Applies logit to vector elements.
Applies logit to vector elements.
(logmeanexp v)
Calculates the numerically stable log of the mean of the exponential of each element in vector v
.
This is equivalent to log(mean(exp(v_i)))
for all elements v_i
in v
.
It provides a numerically stable way to compute log(sum(exp(v_i))) - log(count(v))
by shifting values to prevent overflow during exponentiation.
Often used in machine learning and statistical contexts where dealing with large values inside exponentials is common.
Returns a double value.
Calculates the numerically stable log of the mean of the exponential of each element in vector `v`. This is equivalent to `log(mean(exp(v_i)))` for all elements `v_i` in `v`. It provides a numerically stable way to compute `log(sum(exp(v_i))) - log(count(v))` by shifting values to prevent overflow during exponentiation. Often used in machine learning and statistical contexts where dealing with large values inside exponentials is common. Returns a double value.
(logmxp1 vector)
Applies logmxp1 to vector elements.
Applies logmxp1 to vector elements.
(logsoftmax v)
(logsoftmax v t)
Calculates the element-wise natural logarithm of the softmax function for the given vector v
.
The standard log-softmax of an element $v_i$ is $\log(\operatorname{softmax}(v)_i)$, which is mathematically equivalent to $v_i - \log(\sum_j \exp(v_j))$. This function provides a numerically stable implementation of this calculation, particularly useful for avoiding overflow and underflow issues when dealing with large or small exponential values.
It supports two arities:
[v]
: Computes the standard log-softmax using the numerically stable form.[v t]
: Computes the temperature-scaled log-softmax. Elements are divided by the temperature t
before applying the log-softmax formula, i.e., $\frac{v_i}{t} - \log(\sum_j \wxp(\fac{v_j}{t}))$. The temperature influences the shape of the corresponding softmax output distribution: $t > 1$ softens it, $t < 1$ sharpens it.Log-softmax is frequently used in numerical computations, especially in machine learning (e.g., as part of the cross-entropy loss function) for its superior numerical properties.
Returns a new vector of the same type and dimension as the input.
Calculates the element-wise natural logarithm of the softmax function for the given vector `v`. The standard log-softmax of an element $v_i$ is $\log(\operatorname{softmax}(v)_i)$, which is mathematically equivalent to $v_i - \log(\sum_j \exp(v_j))$. This function provides a numerically stable implementation of this calculation, particularly useful for avoiding overflow and underflow issues when dealing with large or small exponential values. It supports two arities: - `[v]`: Computes the standard log-softmax using the numerically stable form. - `[v t]`: Computes the temperature-scaled log-softmax. Elements are divided by the temperature `t` *before* applying the log-softmax formula, i.e., $\frac{v_i}{t} - \log(\sum_j \wxp(\fac{v_j}{t}))$. The temperature influences the shape of the corresponding softmax output distribution: $t > 1$ softens it, $t < 1$ sharpens it. Log-softmax is frequently used in numerical computations, especially in machine learning (e.g., as part of the cross-entropy loss function) for its superior numerical properties. Returns a new vector of the same type and dimension as the input.
(logsumexp v)
Calculates the LogSumExp of the vector v
.
This is the numerically stable computation of log(sum(exp(x_i)))
for all elements x_i
in v
.
It is often used to prevent overflow when exponentiating large numbers, especially in machine learning and statistics.
Returns a double value.
Calculates the LogSumExp of the vector `v`. This is the numerically stable computation of `log(sum(exp(x_i)))` for all elements `x_i` in `v`. It is often used to prevent overflow when exponentiating large numbers, especially in machine learning and statistics. Returns a double value.
(magsq v)
Returns length of the vector squared.
Returns length of the vector squared.
(make-vector dims)
(make-vector dims xs)
Returns fixed size vector for given number of dimensions.
Proper type is used.
Returns fixed size vector for given number of dimensions. Proper type is used.
(mult v)
(mult v x)
Multiplies vector by number x
.
Multiplies vector by number `x`.
(near-zero? v)
(near-zero? v abs-tol)
(near-zero? v abs-tol rel-tol)
Equality to zero 0
with given absolute (and/or relative) toleance.
Equality to zero `0` with given absolute (and/or relative) toleance.
(nonzero-count v)
Counts non zero velues in vector
Counts non zero velues in vector
(normalize v)
Returns a new vector with the same direction as v
but with a magnitude of 1.
If v
is a zero vector (magnitude is zero), returns a zero vector of the same type.
Returns a new vector with the same direction as `v` but with a magnitude of 1. If `v` is a zero vector (magnitude is zero), returns a zero vector of the same type.
(orthogonal-polynomials xs)
Generates a sequence of orthogonal vectors by evaluating orthogonal polynomials at the points specified in the input sequence xs
.
The output vectors represent the values of orthogonal polynomials evaluated at the elements of xs
. Orthogonality is defined with respect to the discrete inner product based on summation over the points in xs
.
The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree (count xs) - 1
.
This function is useful for constructing orthogonal bases for polynomial approximation or regression on discrete data.
Generates a sequence of orthogonal vectors by evaluating orthogonal polynomials at the points specified in the input sequence `xs`. The output vectors represent the values of orthogonal polynomials evaluated at the elements of `xs`. Orthogonality is defined with respect to the discrete inner product based on summation over the points in `xs`. The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree `(count xs) - 1`. This function is useful for constructing orthogonal bases for polynomial approximation or regression on discrete data.
(orthonormal-polynomials xs)
Generates a sequence of orthonormal vectors by evaluating orthogonal polynomials at the points specified in the input sequence xs
and normalizing the resulting vectors.
The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree (count xs) - 1
. Orthogonality (and thus orthonormality after normalization) is with respect to the discrete inner product based on summation over the points in xs
.
This function produces an orthonormal basis suitable for polynomial approximation or regression on discrete data points defined by xs
, derived from the orthogonal basis computed by orthogonal-polynomials
.
Generates a sequence of orthonormal vectors by evaluating orthogonal polynomials at the points specified in the input sequence `xs` and normalizing the resulting vectors. The sequence starts with the vector for the polynomial of degree 1 and includes vectors up to degree `(count xs) - 1`. Orthogonality (and thus orthonormality after normalization) is with respect to the discrete inner product based on summation over the points in `xs`. This function produces an orthonormal basis suitable for polynomial approximation or regression on discrete data points defined by `xs`, derived from the orthogonal basis computed by [[orthogonal-polynomials]].
(permute v idxs)
Permutes vector elements with given indices.
Permutes vector elements with given indices.
(perpendicular v)
(perpendicular v1 v2)
Perpendicular vector. Only for Vec2
and Vec3
types.
Perpendicular vector. Only for `Vec2` and `Vec3` types.
(pow v exponent)
Applies power to a vector elements.
Applies power to a vector elements.
(pow10 vector)
Applies pow10 to vector elements.
Applies pow10 to vector elements.
(project v1 v2)
Calculates the vector projection of v1
onto v2
.
The projection is a vector along the direction of v2
that represents the component of v1
in that direction.
Calculates the vector projection of `v1` onto `v2`. The projection is a vector along the direction of `v2` that represents the component of `v1` in that direction.
(radians vector)
Applies radians to vector elements.
Applies radians to vector elements.
(real-vector v)
Converts to Apache Commons Math RealVector
Converts to Apache Commons Math RealVector
(relative-angle-between v1 v2)
Returns the difference between the heading of v2
and the heading of v1
.
The heading is the angle relative to the positive primary axis ([1,0,...]).
For 2D vectors, this is the difference between their polar angles.
Returns value from $-2\pi$ to $2\pi$.
See also angle-between
(absolute angle between vectors) and heading
.
Returns the difference between the heading of `v2` and the heading of `v1`. The heading is the angle relative to the positive primary axis ([1,0,...]). For 2D vectors, this is the difference between their polar angles. Returns value from $-2\pi$ to $2\pi$. See also [[angle-between]] (absolute angle between vectors) and [[heading]].
(rint vector)
Applies rint to vector elements.
Applies rint to vector elements.
(rotate v angle)
(rotate v angle-x angle-y angle-z)
Rotates vector. Only for Vec2
and Vec3
types.
Rotates vector. Only for `Vec2` and `Vec3` types.
(round vector)
Applies round to vector elements.
Applies round to vector elements.
(safe-sqrt vector)
Applies safe-sqrt to vector elements.
Applies safe-sqrt to vector elements.
(sec vector)
Applies sec to vector elements.
Applies sec to vector elements.
(sech vector)
Applies sech to vector elements.
Applies sech to vector elements.
(sfrac vector)
Applies sfrac to vector elements.
Applies sfrac to vector elements.
(sgn vector)
Applies sgn to vector elements.
Applies sgn to vector elements.
(shift v)
(shift v x)
Adds a value to every vector element.
Adds a value to every vector element.
(sigmoid vector)
Applies sigmoid to vector elements.
Applies sigmoid to vector elements.
(signum vector)
Applies signum to vector elements.
Applies signum to vector elements.
(sin vector)
Applies sin to vector elements.
Applies sin to vector elements.
(sinc vector)
Applies sinc to vector elements.
Applies sinc to vector elements.
(sinh vector)
Applies sinh to vector elements.
Applies sinh to vector elements.
(size v)
Returns elements count of the vector.
Returns elements count of the vector.
(softmax v)
(softmax v t)
Calculates the softmax function for the given vector v
.
The softmax function transforms a vector of arbitrary real values into a probability distribution, where each element is a value between 0 and 1, and all elements sum to 1.
It has two arities:
[v]
: Computes the standard softmax: softmax(v)_i = exp(v_i) / sum_j(exp(v_j))
.[v t]
: Computes the temperature-scaled softmax: softmax(v)_i = exp(v_i / t) / sum_j(exp(v_j / t))
. The t
parameter (temperature, defaults to 1) controls the shape of the output distribution; higher temperatures produce softer, more uniform distributions, while lower temperatures produce sharper distributions closer to a one-hot encoding.The implementation uses a numerically stable approach (by shifting values based on the vector's maximum) to prevent overflow when exponentiating large numbers.
Returns a new vector of the same type and dimension as the input.
Calculates the softmax function for the given vector `v`. The softmax function transforms a vector of arbitrary real values into a probability distribution, where each element is a value between 0 and 1, and all elements sum to 1. It has two arities: - `[v]`: Computes the standard softmax: `softmax(v)_i = exp(v_i) / sum_j(exp(v_j))`. - `[v t]`: Computes the temperature-scaled softmax: `softmax(v)_i = exp(v_i / t) / sum_j(exp(v_j / t))`. The `t` parameter (temperature, defaults to 1) controls the shape of the output distribution; higher temperatures produce softer, more uniform distributions, while lower temperatures produce sharper distributions closer to a one-hot encoding. The implementation uses a numerically stable approach (by shifting values based on the vector's maximum) to prevent overflow when exponentiating large numbers. Returns a new vector of the same type and dimension as the input.
(sqrt vector)
Applies sqrt to vector elements.
Applies sqrt to vector elements.
(tan vector)
Applies tan to vector elements.
Applies tan to vector elements.
(tanh vector)
Applies tanh to vector elements.
Applies tanh to vector elements.
(to-polar v)
To polar coordinates (2d, 3d only), first element is length, the rest angle.
To polar coordinates (2d, 3d only), first element is length, the rest angle.
Same as vec->Vec
. Deprecated.
Same as [[vec->Vec]]. Deprecated.
(transform v o vx vy)
(transform v o vx vy vz)
Transforms vector.
Maps point to a coordinate system defined by origin, vx, vy and vz (as bases).
Only for Vec2
and Vec3
types.
Transforms vector. Maps point to a coordinate system defined by origin, vx, vy and vz (as bases). Only for `Vec2` and `Vec3` types.
(trunc vector)
Applies trunc to vector elements.
Applies trunc to vector elements.
(vec->RealVector v)
Converts to Apache Commons Math RealVector
Converts to Apache Commons Math RealVector
(vec->seq v)
Converts to sequence (same as seq)
Converts to sequence (same as seq)
(vec->Vec v)
Converts to Clojure primitive vector Vec
.
Converts to Clojure primitive vector `Vec`.
(vec3)
(vec3 [x y z])
(vec3 v z)
(vec3 x y z)
Creates Vec2 vector
Creates Vec2 vector
(vec4)
(vec4 [x y z w])
(vec4 v w)
(vec4 v z w)
(vec4 x y z w)
Creates Vec4 vector
Creates Vec4 vector
(xlogx vector)
Applies xlogx to vector elements.
Applies xlogx to vector elements.
cljdoc builds & hosts documentation for Clojure/Script libraries
Ctrl+k | Jump to recent docs |
← | Move to previous article |
→ | Move to next article |
Ctrl+/ | Jump to the search field |