均值矩阵的构造

时间:2016-08-12 19:52:43

标签: matlab

我想用图像中显示的算法创建矩阵B:我如何从矩阵A中为此算法编写函数?how to create matrix B from matrix A

2 个答案:

答案 0 :(得分:1)

以下代码没有矢量化,只使用简单的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

答案 1 :(得分: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))