-3
我想創建矩陣B與圖像中顯示的算法:我怎麼可以從矩陣A寫這個算法的函數? 平均矩陣的構造
我想創建矩陣B與圖像中顯示的算法:我怎麼可以從矩陣A寫這個算法的函數? 平均矩陣的構造
這裏是另外一個。
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))
下面的代碼是不是矢量,只是使用簡單的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
我不知道該怎麼做。我想到了具有NaN值的爆炸列,然後是爆炸矢量 – masih