Reputation: 115
I have a matrix data
, that I am saving into data_Buffer
. All values <=-999
in data
are replaced by NaN
and stored in data_Buffer
. This is my code:
fid = fopen('D:\Data\');
data = fread(fid,'*int16');% 21 x 200 matrix
fclose(fid);
data(data <= -999) = nan;
s = size(data,2);
data_Buffer(:,k:k+s-1) = data;% This is a buffer to store the data matrix
Questions/requirements:
1) In data_Buffer
, how can I see search for NaN
values in a row and replace them with the previous non-NaN
value? The algorithm should start from the first column and move towards the last column (i.e., if there is a NaN
in column 10, it should be replaced by the valid value from column 9).
2) If there are several consecutive NaN
values, they should be replaced by the previous non-NaN
value in the row.
Upvotes: 1
Views: 834
Reputation: 115
I solved it using the solution provided by Matt at Matlab Central and modified it for case of rows instead of columns:
function A = fill_nans(A)
% Replaces the NaN in each column with
% previous non-NaN values.
for i = 1:size(A,1)
I = A(1,i);
for j = 2:size(A,2)
if isnan(A(i,j))
A(i,j) = I;
else
I = A(i,j);
end
end
Upvotes: 1