MATLAB: Replace NaN by using for loop

for loopnanreplace nan

I have a set of data (call it 'dataset') which is a 1000*1000 table with NaN, NaN appear start from row 381 to the end. I design to use for loop to find the mean number from row 1 to row 380 in each column and use it to replace the NaN in that column. I have write the condition but get stuck for the loop because I have no idea code the loop.(I'm a matlab beginner)
dataset = table2array(dataset); %convert table to matrix for modify data
columns = size(dataset,2);
for i = 2:1:columns - 1 %start from second column, end at second last column
MeanNo = mean(dataset(1:380,i)); %get the mean number from row 1 to row 380 for one column
dataset(isnan(1:end,i)) = MeanNo; %replace NaN with the mean number just got
end
dataset = array2table(dataset); %convert back to table
That is my code and it cannot be run, I have no idea how can I solve it

Best Answer

One approach:
dataset = [randi(9, 10, 5); NaN(10, 5)]; % Create Data
dataset_mean = mean(dataset, 'omitnan'); % Column Mean Omitting ‘NaN’ Values
dataset_new = dataset; % Create Duplicate
idx = isnan(dataset_new); % NaN == 1, Others == 0
dataset_new(idx) = 0; % Set ‘NaN’ Values = 0
dataset_new = dataset_new + bsxfun(@times, idx, dataset_mean); % Add ‘Replacement’ Values To ‘dataset_new’