Matlab 均值矩阵的构造

Matlab 均值矩阵的构造,matlab,Matlab,我想用图中所示的算法创建矩阵B:如何从矩阵a为该算法编写函数?以下代码不是矢量化的,只是使用简单的for和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

我想用图中所示的算法创建矩阵B:如何从矩阵a为该算法编写函数?

以下代码不是矢量化的,只是使用简单的for和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
这是另一个

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))

我不知道该怎么做。我想到用NaN值分解列,然后表示分解向量