2016-08-12 11 views
-3

行列Bを画像に示されたアルゴリズムで作成したいのですが、行列Aからこのアルゴリズムに関数を書く方法はありますか? how to create matrix B from matrix Aは、次のコードはベクトル化されていない平均行列の構成

+0

私はそのことを知りません。私はNaN値で列を分解し、次に分解されたベクトル – masih

答えて

1

をここでは別のものです。

A = [1 3 4; 3 4 2; 3 2 NaN; NaN 3 2; NaN 2 3; NaN NaN 5; 2 NaN 1; 1 5 4]; 
tmpA = A(:); 

% nans includes all nans and column breaks (after the comma) 
nans = sort([find(isnan(A(:)))',size(A,1)+1:size(A,1):numel(A)+1-size(A,1)]); 

pivot = 1; skip = 0; 
for n = nans 
    if (n == pivot+1) % previous entry was already a NaN 
     skip = 1; % turn skip on to skip repeated nans 
    else 
     tmpA(pivot+skip:n-1) = mean(tmpA(pivot+skip:n-1)); 
     skip = 0; % turn skip off. 
    end 
    pivot = n; 
end 
    tmpA(nans(end)+1:end) = mean(A(nans(end)+1:end)); 

result = reshape(tmpA,size(A)) 
1

だけのためとwhileループの単純な使用していますが、それは、パズルを解く...

A = [1 3 4 
    3 4 2 
    3 2 NaN 
    NaN 3 2 
    NaN 2 3 
    NaN NaN 5 
    2 NaN 1 
    1 5 4]; 

B = A; 

for x = 1:size(A, 2) 
    C = A(:, x); %Get column of A; 

    y0 = find(~isnan(C), 1); %Find first number in column C 

    while (~isempty(y0)) 
     y1 = find(isnan(C(y0:end)), 1) + y0-1; %Find first NaN from y0 to end 

     if (isempty(y1)) 
      y1 = size(A, 1); %NaN not found, so reached end of column 
     else 
      y1 = y1 - 1; %y1 is row of last number in the group. 
     end 

     group_mean = mean(C(y0:y1)); %Compute mean from y0 to t1. 
     B(y0:y1, x) = group_mean; %Fill all group elements with group mean. 

     if (y1 == size(A, 1)) 
      y0 = []; %y1 reached the end. 
     else 
      y0 = find(~isnan(C(y1+1:end)), 1) + y1; %Find next number from y1 to end 
     end 
    end 
end 

結果:

B = 

    2.3333 2.8000 3.0000 
    2.3333 2.8000 3.0000 
    2.3333 2.8000  NaN 
     NaN 2.8000 3.0000 
     NaN 2.8000 3.0000 
     NaN  NaN 3.0000 
    1.5000  NaN 3.0000 
    1.5000 5.0000 3.0000