This workflow receives an array of vectors in JSON format, validates that all vectors have the same dimensions, and computes the centroid. It is designed to be reusable across different projects.
Receive Vectors (Webhook) : Accepts a GET request containing an array of vectors in the vectors parameter.
vectors parameter in JSON format./webhook/centroid?vectors=[[2,3,4],[4,5,6],[6,7,8]]Extract & Parse Vectors (Set Node): Converts the input string into a proper JSON array for processing.
Ensuresvectors is a valid array.
If the parameter is missing, it may generate an error.
Expected Output Example:
{ "vectors": [[2,3,4],[4,5,6],[6,7,8]] }
Validate & Compute Centroid (Code Node): Validates vector dimensions and calculates the centroid.
Validation: Ensures all vectors have the same number of dimensions.
Computation: Averages each dimension to determine the centroid.
If validation fails: Returns an error message indicating inconsistent dimensions.
Successful Output Example:
{ "centroid": [4,5,6] }
Error Output Example:
{ "error": "Vectors have inconsistent dimensions." }
Return Centroid Response (Respond to Webhook Node) : Sends the final response back to the client.
If the computation is successful , it returns the centroid.
If an error occurs , it returns a descriptive error message.
Example Response:
{ "centroid": [4, 5, 6] }
{
  "vectors": [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ]
}
Receive Vectors) to receive JSON input.Extract & Parse Vectors) to extract and convert the data.Validate & Compute Centroid) to:
Return Centroid Response) to return the result.const input = items[0].json;
const vectors = input.vectors;
if (!Array.isArray(vectors) || vectors.length === 0) {
  return [{ json: { error: "Invalid input: Expected an array of vectors." } }];
}
const dimension = vectors[0].length;
if (!vectors.every(v => v.length === dimension)) {
  return [{ json: { error: "Vectors have inconsistent dimensions." } }];
}
const centroid = new Array(dimension).fill(0);
vectors.forEach(vector => {
  vector.forEach((val, index) => {
    centroid[index] += val;
  });
});
for (let i = 0; i < dimension; i++) {
  centroid[i] /= vectors.length;
}
return [{ json: { centroid } }];
This workflow provides a simple yet flexible solution for vector centroid computation, ensuring validation and reliability.


