2012-11-17 92 views
0

我正在嘗試查找矩陣中某些座標的總和。在Matlab中添加矩陣的特定座標

我有一個N x M矩陣。我有一個包含2xM值的向量。向量中的每一對值都是矩陣中的一個座標。因此它們的座標數是M。我想查找所有座標的總和而不使用for循環。

是否有矩陣操作我可以用來得到它?

感謝

+0

總和?或這些座標值的總和? –

回答

2

據我瞭解的載體包含(行,列)座標矩陣元素。您可以將它們轉換爲矩陣元素數字索引。這個例子展示瞭如何去做。我假設你的座標向量看起來像這樣: [正coordinate1 M-coordinate1正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

如果你想找到你2xM陣列coords的心,那麼你可以簡單地寫

centroid = mean(coords,2) 

如果你想找到的加權質心,其中每個座標對被加權在MxN陣列A在相應的條目,就可以使用sub2ind這樣的:

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

weights = A(idx); 

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

如果你想要的是所有這些座標點,你可以做上面的,只是總結的權重項之和:

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

weights = A(idx); 

sumOfValues = sum(weights); 
+0

哦,是的sub2ind功能。它比我的vector(1:2:end)+(vector(2:2:end)-1)* n) - > upvote更漂亮。但我明白指數是在一個向量中,而不是一個矩陣。 – solimanelefant

+0

@solimanelefant:我假設'2xM'的意思是'2-by-M',所以索引應該在數組的每一列中。不過,我同意這個問題不是很明確。 – Jonas

+0

@solimanelefant一個向量只是一個一維矩陣 –