2016-06-21 117 views
0

该帖子跟进另一个柱的最大值:find common value of one matrix in another matrix意味着基于矩阵

正如我解释,我有一个矩阵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); 实施例线I得到以M:

6.95 
6.23 
3.24 
7.20 

现在,我想的2个值之前和最大值之后在myMatrix的选择,比如M发现,我将需要计算这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 

并在MyMatrix中创建一个具有这5个值的平均值的新列。

继@丹的代码,从以前的帖子采取:

colInd = bsxfun(@plus,PeakInd, -2:2); 
MyMatrixT = MyMatrix.'; 
rowIndT = colInd.'; 
linIndT = bsxfun(@plus,rowIndT,0:size(MyMatrixT,1):size(MyMatrixT,1)*(size(MyMatrixT,2)-1)); 
resultT = MyMatrixT(linIndT); 
result = resultT.'; 
mean(result,2) 
MyMatrix = [MyMatrix, mean(result,2)]; 

下面是帖子的新部件,关于这个问题时,最大值是边缘附近。 当最大值是MyMatrix的第一列或最后一列时,我想要有NaN。

相反,当最大值在第二列时,我想计算考虑最大值,最大值和最大值之后的两列之前的一列的平均值。

虽然当最大值位于倒数第二列时,我想考虑最大值,最大值之前的两列以及最大值之后的一列。

如果你能帮助我,我将不胜感激。非常感谢!

+0

敢肯定这是我的第二个代码所做的只是使用'nanmean'。所以如果你的最大值在第2列,那么你会得到类似于[NaN,6,10,4,2]的东西''所以'nanmean'会给你'[6,10,4,2]'的平均值使用1列预备和两列后面的最大... – Dan

+0

只有添加关于@丹的评论是为了得到'NaN'如果你的最大值是在第一个或最后一列,你只需要改变它结束。(假设您要添加的列名为'M2',原始矩阵的列数为'N',则需要调用'M2(Ind == 1 | Ind == N)= NaN;') – BillBokeey

+0

@BillBokeey否我的意思是我已经在这里完全回答了这个问题http://stackoverflow.com/a/37705364/1011724 – Dan

回答

1

而不是创建一个二维数组的NaN加nanmean的,你可以使用min/max得到正确的指标:

pad = 2; 
[~, Ind] = max(MyMatrix, [], 2); 
minCol = max(1, Ind-pad); 
maxCol = min(size(MyMatrix, 2), Ind+pad); 
result = arrayfun(@(row, min_, max_) mean(MyMatrix(row, min_:max_)),... 
        (1:size(MyMatrix, 1)).', minCol, maxCol); 
0

如果您有图像处理工具箱,你也可以使用padarray,例如

B = padarray(magic(5),[0 2],NaN); 

B = 

    NaN NaN 17 24  1  8 15 NaN NaN 
    NaN NaN 23  5  7 14 16 NaN NaN 
    NaN NaN  4  6 13 20 22 NaN NaN 
    NaN NaN 10 12 19 21  3 NaN NaN 
    NaN NaN 11 18 25  2  9 NaN NaN 

(...如果你没有padarray做什么,只是手动添加两边2 NaN的列),然后使用一些bsxfun + sub2ind我们得到期望的结果:

pad_sz = 2; 
B = padarray(magic(5),[0 pad_sz],NaN); 
[~,I] = nanmax(B,[],2); % by using nanmax we "explicitly" say we ignore NaNs. 
colInd = bsxfun(@plus,-pad_sz:pad_sz,I); 
linearInd = sub2ind(size(B), repmat((1:5).',[1,size(colInd,2)]), colInd); 
picks = B(linearInd); 
res = nanmean(picks,2); 
% or combine the last 3 lines into: 
% res = nanmean(B(sub2ind(size(B), repmat((1:5).',[1,size(colInd,2)]), colInd)),2); 
res = res + 0./~(I == pad_sz+1 | I == size(B,2)-pad_sz); %add NaN where needed. 
+0

'这样的调用上输出非NaN值。感谢您的回复。然而,我只想当NaN的意思是,只有当最大值在第一列或最后一列(没关系,如果最大值在第二或第二列)。 – dede

+0

@dede - 查看更新的答案。 –