每行獲取所需的列索引:
colInd = bsxfun(@plus,Ind, -2:2)
現在,它實際上是更容易與您的矩陣轉置(MyMatrixT = MyMatrix.'
),因爲我們將與線性索引來工作,所以我們寧願用
努力工作
rowIndT = colInd.';
現在我們要將此Rind
轉換爲線性索引。這僅僅是添加行的總數(原列數)的列數的情況下
linIndT = bsxfun(@plus,rowIndT,0:size(MyMatrixT,1):size(MyMatrixT,1)*(size(MyMatrixT,2)-1))
最後,我們提取值和轉回來
resultT = MyMatrixT(linIndT);
result = resultT.'
result =
2.5100 6.3100 6.9500 4.9700 2.9100
5.8700 6.1800 6.2300 5.2000 4.8600
-3.5500 0.5200 3.2400 -7.7700 -8.4300
3.4000 6.5600 7.2000 4.3000 -0.7700
新列結果是剛剛平均:
mean(result,2)
,並把它添加到您的矩陣
MyMatrix = [MyMatrix, mean(result,2)]
現在仍然有一個問題,如果最大值接近邊緣會發生什麼(即,如果最大值在列2中,則最大值之前的兩個值未被定義)。如何處理這個問題需要你首先定義你在這種情況下所需要的行爲。但是讓我們假設你想NaN
,那麼我會做到這一點:
colInd = bsxfun(@plus,Ind, -2:2);
rowIndT = colInd.';
% Bound rowIndT to be between 1 and size(MyMatrixT,1)
rowIndT(rowIndT < 1) = 1;
rowIndT(rowIndT > size(MyMatrixT,1)) = size(MyMatrixT,1);
linIndT = bsxfun(@plus,rowIndT,0:size(MyMatrixT,1):size(MyMatrixT,1)*(size(MyMatrixT,2)-1)); % You can use sub2ind instead for this step
result = MyMatrixT(linIndT).';
% Now go back and put NaNs where they are needed
nanColInd = colInd < 1 | colInd > size(MyMatrix,2);
result(nanColInd) = NaN;
% Now use nanmean to ignore any NaNs when finding the mean
MyMatrix = [MyMatrix, nanmean(result,2)]
最後一件事,你可能會發現它更直觀的使用sub2ind
以找到線性指標。在這種情況下
linIndT = bsxfun(@plus,rowIndT,0:size(MyMatrixT,1):size(MyMatrixT,1)*(size(MyMatrixT,2)-1))
成爲
linIndT = sub2ind(size(MyMatrixT), rowIndT, repmat(1:size(MyMatrixT,2),size(rowIndT,1),1))
+1優秀。所有的基地似乎都有很好的解釋,做得很好。我希望SO會讓更多的選票質量。 – Matt
非常感謝您的幫助和解釋@丹!非常感激。 – dede
@Dan如果只有當最大值是MyMatrix的第一列或最後一列時才需要NaN,我該如何更改代碼的最後部分?相反,當最大值在第二列時,我想計算考慮最大值之前的一列,最大值和最大值之後的兩列的平均值。而當最大值位於倒數第二列時,我想考慮最大值,最大值之前的兩列以及最大值之後的一列。 – dede