行列内の特定の座標の合計を見つけようとしています。
N x M
マトリックスがあります。値を含むベクトルがあり2xM
ます。ベクトル内の値のすべてのペアは、行列内の座標です。したがって、それらはM
座標の数です。forループを使用せずにすべての座標の合計を求めたい。
これを取得するために使用できる行列演算はありますか?
ありがとう
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);
私が理解しているように、ベクトルには行列要素への(行、列)座標が含まれています。それらを行列要素番号インデックスに変換するだけです。この例は、その方法を示しています。あなたの座標ベクトルは次のようになっていると思います:[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