我有一个矩阵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
Run Code Online (Sandbox Code Playgroud)
我已经确定了矩阵MyMatrix的每一行的最大值如下:
[M Ind] = max(MyMatrix, [], 2);
Run Code Online (Sandbox Code Playgroud)
我在M中获得的示例行:
6.95
6.23
3.24
7.20
Run Code Online (Sandbox Code Playgroud)
现在,我想在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
Run Code Online (Sandbox Code Playgroud)
并使用这5个值的平均值在MyMatrix中创建一个新列.
我将不胜感激任何帮助.非常感谢.
获取每行所需的列索引:
colInd = bsxfun(@plus,Ind, -2:2)
Run Code Online (Sandbox Code Playgroud)
现在,使用矩阵转置(MyMatrixT = MyMatrix.')实际上会更容易,因为我们将使用线性索引,所以让我们更好地使用
rowIndT = colInd.';
Run Code Online (Sandbox Code Playgroud)
现在我们要将其转换Rind为线性索引.这只是将总行数(原始列数)添加到列号的情况
linIndT = bsxfun(@plus,rowIndT,0:size(MyMatrixT,1):size(MyMatrixT,1)*(size(MyMatrixT,2)-1))
Run Code Online (Sandbox Code Playgroud)
最后我们提取值并转换回来
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
Run Code Online (Sandbox Code Playgroud)
新列只是结果的平均值:
mean(result,2)
Run Code Online (Sandbox Code Playgroud)
并将其附加到您的矩阵
MyMatrix = [MyMatrix, mean(result,2)]
Run Code Online (Sandbox Code Playgroud)
现在仍然存在一个问题,如果最大值接近边缘会发生什么(即如果最大值在第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)]
Run Code Online (Sandbox Code Playgroud)
最后一点,您可能会发现使用它sub2ind来查找线性索引更直观.在这种情况下
linIndT = bsxfun(@plus,rowIndT,0:size(MyMatrixT,1):size(MyMatrixT,1)*(size(MyMatrixT,2)-1))
Run Code Online (Sandbox Code Playgroud)
变
linIndT = sub2ind(size(MyMatrixT), rowIndT, repmat(1:size(MyMatrixT,2),size(rowIndT,1),1))
Run Code Online (Sandbox Code Playgroud)