0

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

1
  • sum of the coordinates? or sum of the values at these coordinates? Commented Nov 17, 2012 at 14:34

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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);

2 Comments

Oh yes the sub2ind function. It's prettier than my vector(1:2:end) + (vector(2:2:end)-1)*n) -> upvote. But I understood that the indices are in a vector, not a matrix.
@solimanelefant: I assume 2xM means 2-by-M, so indices would be in each column of the array. I agree, though, the question is not super clear on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.