我试图在矩阵中找到某些坐标的总和。
我有一个N x M
矩阵。我有一个包含2xM
值的向量。向量中的每一对值都是矩阵中的一个坐标。因此它们是M
坐标数。我想在不使用 for 循环的情况下找到所有坐标的总和。
有没有我可以用来得到这个的矩阵运算?
谢谢
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);
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