每行获取所需的列索引:
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