2012-06-10 42 views
1

假设我有以下矩阵: 一个=替换第一(x个)非楠与楠

2 NaN NaN 
4 NaN  3 
3  7  9 
5 12  5 
8 10  8 
12  5 10 

我需要与楠每一列来替换第x个非楠值。

如果要替换值的数目为x = 3,则新的矩阵应该是:

B =

NaN NaN NaN 

NaN NaN NaN 

NaN NaN NaN 

5  NaN NaN 

8  NaN 8 

12 5  10 

任何想法如何做到这一点?

在此先感谢。

回答

2

这里是另一个量化代码:

%# given the data 
a = [ 2 NaN NaN; 4 NaN 3; 3 7 9; 5 12 5; 8 10 8; 12 5 10 ] 
x = 3 

%# replace with NaNs 
sz = size(a); 
d = [ones(1,sz(2)) ; diff(~isnan(a))]; 
rIdx = arrayfun(@(k) find(d(:,k),1,'last'), 1:sz(2)); 
ind = bsxfun(@plus, sub2ind(sz, rIdx, 1:sz(2)), (0:x-1)'); 
a(ind(:)) = NaN; 

首先,我们检查非楠元素,那么我们diff横跨行的结果。我们在每列中找到最后一个1的位置,转换为线性索引并将偏移量x添加到每个列。最后我们用计算的指数替换为NaN s。

2

循环遍历列,然后在每个柱的成员循环,与南更换前3个非NaN的数字:

for c = 1:size (a,2) 
    col = a (:,c); 
    replaced = 0; 
    for r = 1:size (col) 
    if (~isnan (col (r))) 
     a (r,c) = Nan; 
     replaced = replaced + 1 
     if (replaced == 3) 
     break; 
     end 
    end 
    end 
end 

我认为应该这样做

+0

我会试试,谢谢 – mario

+0

我实际上没有尝试过运行它,所以我可能已经搞砸了一些语法(我不使用Matlab很多),但应该大多数是正确的,我认为 – lxop

+0

是的!效果很好,再次感谢 – mario

-1
class TestNan 
{ 
    public static void main(String[] args) 
    { 
     double[][] mat = new double[6][3]; 
     //initialize the matrix here 
     for(int i = 0; i<3; i++) 
     { 
      int x = 3; // no. of numbers to be replaced 
      for(int j = 0; j<6; j++) 
      { 
       if(x == 0) 
        break; 
       Double d = Double.valueOf(mat[i][j]); 
       if(!d.isNaN()) 
       { 
        d = Double.NaN; 
        x--; 
       } 
      } 
     } 
     //Print your matrix here 
    } 
} 

尝试这个,让我知道如果你遇到任何问题!

+1

错误的语言。 –

2

这是一个矢量化的解决方案。首先将a(将用新的NaN s替换的部分)的顶部取入aTopMatrix。然后把a的下半部分变成aLowMatrix。然后根据aTopMatrix中预先存在的NaN值,使用逻辑寻址代替aLowMatrix的值与NaN。最后,创建一个大小为x x size(a,2)NaN数组,并将其与aLowMatrix垂直连接以获得b中所需的结果矩阵。

%定义示例数据:

a = [ 2 NaN NaN; 4 NaN 3; 3 7 9; 5 12 5; 8 10 8; 12 5 10 ] 
x = 3 

%下面的代码:

aTopMatrix = a(1:x, 1:end); 
aLowMatrix = a(x+1:end, 1:end); 
aLowMatrix(isnan(aTopMatrix)) = NaN; 
b = [ ones(x, size(a,2))*NaN; aLowMatrix ]; 
+0

作品很美,谢谢! – mario

+0

如果矩阵高度不是6(NaNs所需数量的两倍),那么这将无法正常工作,如果NaN之间存在非Nan间隙(例如第4栏Nan 3 Nan 4 3 2) 。 如果矩阵总是这样的大小,然而NaN总是聚集在顶部,然而这很有效。 – lxop