Published
Edited
Oct 4, 2020
Importers
Insert cell
md`# Vector Math`
Insert cell
function vecScale(vec, scalar) {
return vec.map(v => scalar * v);
}
Insert cell
function vecAdd(u, v) {
return zip(u, v).map(([uu, vv]) => uu + vv);
}
Insert cell
function vecSub(u, v) {
return u.map((d, i) => d - v[i]);
}
Insert cell
function vecMix(u, v, a) {
return zip(u, v).map(([uu, vv]) => uu * (1 - a) + vv * a);
}
Insert cell
function vecMag(u) {
return u.length ? Math.pow(sum(u.map(d => d ** 2)), 1 / u.length) : 0;
}
Insert cell
function vecAbs(u) {
return u.map(d => Math.abs(d));
}
Insert cell
function vecMax(u, val) {
return u.map(d => Math.max(d, val));
}
Insert cell
function vecDot(u,v) {
return sum(zip(u,v).map(([uu,vv]) => uu * vv))
}
Insert cell
function sum(vs) {
return vs.reduce((p, c) => p + c, 0);
}
Insert cell
function zip(u, v) {
return u.map((d, i) => [d, v[i]]);
}
Insert cell
function vec2Mag([ux, uy]) {
return Math.sqrt(ux ** 2 + uy ** 2);
}
Insert cell
function vec2Angle(u, v) {
const [ux, uy] = u;
const [vx, vy] = v;
const sign = ux * vy - uy * vx >= 0 ? 1 : -1;
return sign * Math.acos(vec2Dot(u, v) / (vec2Mag(u) * vec2Mag(v)));
}
Insert cell
function vec2Dot([ux, uy], [vx, vy]) {
return ux * vx + uy * vy;
}
Insert cell
function vec2Add([ux, uy], [vx, vy]) {
return [ux + vx, uy + vy];
}
Insert cell
function mat2DotVec2([m00, m01, m10, m11], [vx, vy]) {
return [m00 * vx + m01 * vy, m10 * vx + m11 * vy];
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more