我有一个矩阵 MyMatrix 2549x13double
来自 MyMatrix 的几个示例行:
-7.80 -4.41 -0.08 2.51 6.31 6.95 4.97 2.91 0.66 -0.92 0.31 1.24 -0.07
4.58 5.87 6.18 6.23 5.20 4.86 5.02 5.33 3.69 1.36 -0.54 0.28 -1.20
-6.22 -3.77 1.18 2.85 -3.55 0.52 3.24 -7.77 -8.43 -9.81 -6.05 -5.88 -7.77
-2.21 -3.21 -4.44 -3.58 -0.89 3.40 6.56 7.20 4.30 -0.77 -5.09 -3.18 0.43
我已确定矩阵 MyMatrix 的每一行的最大值如下:
[M Ind] = max(MyMatrix, [], 2);
我在 M 中获得的示例行:
6.95
6.23
3.24
7.20
现在,我想在MyMatrix中选择 M 中最大值之前和之后的2个值,因为我需要计算这5个值的平均值。 所以,在这个例子中,我想选择:
2.51 6.31 6.95 4.97 2.91
5.87 6.18 6.23 5.20 4.86
-3.55 0.52 3.24 -7.77 -8.43
3.40 6.56 7.20 4.30 -0.77
并使用这5个值的平均值在 MyMatrix 中创建一个新列。
我将不胜感激任何帮助。 非常感谢。
答案 0 :(得分:5)
获取每行所需的列索引:
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 :(得分:1)
这将在最大值之前和之后采用平均2个元素,并将其存储在结束列
中endRow = size(MyMatrix,2) + 1
for i = 1:size(MyMatrix,1)
MyMatrix(i,endRow) = mean(MyMatrix(i,max(Ind(i)-2,0):min(Ind(i)+2,end)));
end
更新:抱歉,我已更新了最后一栏中的哪些商店