How to efficiently replace NAN with Numirical value a reference vector

1 回表示 (過去 30 日間)
balandong
balandong 2019 年 2 月 8 日
回答済み: balandong 2019 年 2 月 8 日
Dear User,
As per the title, may I know how to make the following code much compact and efficient. I wonder if the number of FOR-Loops can be reduced further?
Thanks in advance.
Refr=[1 20 1 4 5 2];
WithNan=[1 NaN 1 3 2 2;
1 2 1 NaN 50 2;
NaN NaN 4 9 NaN NaN;
NaN NaN NaN 9 NaN NaN];
NoNan=zeros(size(WithNan,1),size(WithNan,2));
for f_x=1:size(WithNan,1)
SelctCase=WithNan(f_x,:);
NaNLoc=find (isnan(SelctCase));
RefForNaN=Refr(NaNLoc);
for f_xx=1:size(NaNLoc,2)
SelctCase(NaNLoc(f_xx))=RefForNaN(f_xx);
end
NoNan(f_x,:)=SelctCase;

回答 (2 件)

Guillaume
Guillaume 2019 年 2 月 8 日
編集済み: Guillaume 2019 年 2 月 8 日
Certainly, the inner for loop is unnecessary (and the find, use logical indexing).
Refr=[1 20 1 4 5 2];
WithNan=[1 NaN 1 3 2 2;
1 2 1 NaN 50 2;
NaN NaN 4 9 NaN NaN;
NaN NaN NaN 9 NaN NaN];
NoNan = WithNan;
for row = 1:size(WithNan, 1)
toreplace = isnan(WithNan(row, :));
NoNan(row, toreplace) = Refr(toreplace);
end
But loops are not needed at all:
NoNan = WithNan;
filler = repmat(Refr, size(NoNan, 1), 1);
NoNan(isnan(NoNan)) = filler(isnan(NoNan));

balandong
balandong 2019 年 2 月 8 日
Thanks for the quick response. While your approach look elegant, but it consume to much memory if the array become larger. As for my case, WithNan (50 * 500). However, I did not specify about the dimension issue in the original question. Anyhow, II really appreciate for your response.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by