Michael
Michael

Reputation: 3

Matlab: Replace NaN element values by value of the precious row

I'm trying to replace all my matrix's NaN values by the value of the element in the previous row. How can I do that? This is what I tried (for the first column only) but somehow it doesn't work...

for i=1:1935 %number of rows
if RSPB0916v05NEW5(i,1)==NaN  
    RSPB0916v05NEW5(i,1) = RSPB0916v05NEW5((i-1),1) 
end
end

Thanks so much for your help, much appreciated!

Best,

Michael

Upvotes: 0

Views: 107

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

Assuming you do not have NaN in the first row, and remembering that NaN is never equal to NaN:

for ii=2:size(RSPB0916v05NEW5,1)%number of rows
    idx=find(isnan(RSPB0916v05NEW5(ii,:))); % find the index of NaNs
    RSPB0916v05NEW5(ii,indx)=RSPB0916v05NEW5(ii-1,indx); % replace them from the previous row
end

Note that if the first row has NaN values, you need to handle it separately.

Upvotes: 1

Related Questions