MATLAB / Octave, 18 16 bytes
Thanks to user beaker and Don Muesli for removing 2 bytes!
Given that the coordinates are in a N x 2
matrix x
where the first column is the X coordinate and the second column is the Y coordinate, and the masses are in a 1 x N
matrix y
(or a row vector):
@(x,y)y*x/sum(y)
The explanation of this code is quite straight forward. This code performsis an anonymous function that takes in the two inputs x
and y
. We perform the weighted summation (the numerator expression of each coordinate) in a linear algebra approach using matrix-vector multiplication. By taking the vector y
of masses and multiplying this with the matrix of coordinates x
by matrix-vector multiplication, you would compute the weighted sum of both coordinates individually, then we divide each of these coordinates by the sum of the masses thus finding the desired centre of mass returned as a 1 x 2 row vector for each coordinate respectively.
Example runs
>> A=@(x,y)y*x/sum(y)
A =
@(x,y)y*x/sum(y)
>> x = [0 2; 3 4; 0 1; 1 1];
>> y = [2 6 2 10];
>> A(x,y)
ans =
1.4000 2.0000
>> x = [3 1; 0 0; 1 4];
>> y = [2 4 1];
>> A(x,y)
ans =
1.0000 0.8571