0
votes

I am trying to find the sum of certain coordinates in a matrix.

I have a N x M matrix. I have a vector which contains 2xM values. Every pair of values in the vector is a coordinate in the matrix. Hence their are M number of coordinates. I want to find the sum of all of the coordinates without using a for loop.

Is there a matrix operation I can use to get this?

Thanks

2
sum of the coordinates? or sum of the values at these coordinates? - Gunther Struyf

2 Answers

2
votes

As I understand it the vector contains the (row,column) coordinates to the matrix elements. You can just transform them into matrix element number indices. This example shows how to do it. I'm assuming that your coordinate vector looks like this: [n-coordinate1 m-coordinate1 n-coordinate2 m-coordinate2 ...]

n = 5; % number of rows
m = 5; % number of columns
matrix = round(10*rand(n,m)); % An n by m example matrix
% A vector with 2*m elements. Element 1 is the n coordinate, 
% Element 2 the m coordinate, and so on. Indexes into the matrix:
vector = ceil(rand(1,2*m)*5); 
% turn the (n,m) coordinates into the element number index:
matrixIndices = vector(1:2:end) + (vector(2:2:end)-1)*n); 
sumOfMatrixElements = sum(matrix(matrixIndices)); % sums the values of the indexed matrix elements
2
votes

If you want to find the centroid of your 2xM array coords, then you can simply write

centroid = mean(coords,2)

If you want to find the weighted centroid, where each coordinate pair is weighted by the corresponding entry in the MxN array A, you can use sub2ind like this:

idx = sub2ind(size(A),coords(1,:)',coords(2,:)');

weights = A(idx);

weightedCentroid = sum( bsxfun( @times, coords', weights), 1 ) / sum(weights);

If all you want is the sum of all the entries to which the coordinates point, you can do the above and simply sum the weights:

idx = sub2ind(size(A),coords(1,:)',coords(2,:)');

weights = A(idx);

sumOfValues = sum(weights);