filling nans between two values

2 ビュー (過去 30 日間)
joseph Frank
joseph Frank 2011 年 9 月 1 日
Hi,
I have matrices in which I want to fill the nans with the last available number. for example: A=[ 1 nan;nan 3;nan 2;4 nan;nan nan]; I want it to become A=[ 1 nan;1 3;1 2;4 2;4 2]; Is there an easy way of replacing these nans without running a loop. I have large matrices and I need to do this frequently. So,I am wondering if an easy command exists.

採用された回答

Andrei Bobrov
Andrei Bobrov 2011 年 9 月 1 日
A=[ 1 nan;nan 3;nan 2;4 nan;nan nan]
A(A==0)=inf;
A0 = A;
A0(isnan(A0)) = 0;
n0 = A0~=0;
A1 = A0(n0);
idn = cumsum(n0);
idn(idn==0)=nan;
idx = bsxfun(@plus,idn,[0 idn(end,1:end-1)]);
idx2 = idx;
tnn = isnan(idx2);
idx2(tnn)=1;
out = A1(idx2);
out(tnn)=nan;
out(isinf(out))=0;
small corrections
Aoz = A==A;
A1 = A(Aoz);
i1 = cumsum(Aoz);
im = bsxfun(@plus,[0 i1(end,1:end-1)]);
out = A1(im);
out(i1==0)=nan;
last variant
Aoz = A==A;
A1 = A(Aoz);
i1 = cumsum(Aoz);
im = bsxfun(@plus,i1,[0 cumsum(i1(end,1:end-1))]);
out = A1(im+(im==0));
out(i1==0)=nan;
more variant with use reshape
>> A
A =
NaN 0 NaN 0
6 NaN 6 2
0 3 6 NaN
NaN 6 3 NaN
NaN 6 5 6
>> Aoz = A==A;
A1 = A(Aoz);
i2 = reshape(cumsum(Aoz(:)),size(Aoz));
out = A1(i2+(i2==0));
out(cumsum(Aoz)==0)=nan
out =
NaN 0 NaN 0
6 0 6 2
0 3 6 2
0 6 3 2
0 6 5 6
>>
  1 件のコメント
Oleg Komarov
Oleg Komarov 2011 年 9 月 1 日
Vectorized! +1

サインインしてコメントする。

その他の回答 (1 件)

Oleg Komarov
Oleg Komarov 2011 年 9 月 1 日
EDITED
Polished and robustified version of Andrei's algorithm:
A = [NaN NaN
1 NaN
NaN 2
4 0
NaN NaN];
% Index non NaNs and store elements
idxEl = ~isnan(A);
nnNaN = [0; A(idxEl)];
% Positions to non NaN elements
pos = cumsum(idxEl);
% Detect initial NaNs
idxNaN = pos == 0;
% Adust pos with offset for number of non NaN elements in each column
offs = cumsum([1 sum(idxEl(:,1:end-1))]);
pos = bsxfun(@plus,pos,offs);
% Output
B = nnNaN(pos);
% Place back initial NaNs
B(idxNaN) = NaN
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 9 月 1 日
Hi Oleg! Thanks a lot for your vote and cod.
I too corrected my last variant
+1.
Oleg Komarov
Oleg Komarov 2011 年 9 月 1 日
Thanks but all the merit goes to you. No idea, no risk for small corrections :).

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by