Randomly changing elements in an array to NaN's using a for loop

6 views (last 30 days)
I want to be able to change a random 10% of an array to an NaN value, and save it to the matrix I have set up.
So far I have:
a = randn(100,1);
b = repmat(a,1,10);
Where, the matrix is 10 columns of the same numbers. In each column I would like to randomly change 10% of those values to NaN's and have it so these random elements do not overlap (i.e. having two or more consecutive NaN's). I want to do this for all 10 columns, so I am looking to use a for loop. I would like to have all the NaN's and random data in the matrix at the end.
Please help! Thank you in advance!

Answers (1)

Sebastian Castro
Sebastian Castro on 14 Jul 2017
Edited: Sebastian Castro on 14 Jul 2017
I ran through this for one column. A while-loop worked for me
The basic algorithm is:
  1. Generate a random index
  2. Check if the index is valid, i.e., it is not already set to NaN and doesn't have a consecutive one already added
  3. If valid, set that element to NaN
  4. Else, regenerate another index
  5. Keep going until the number of NaNs is 10
a = randn(100,1);
numElems = size(a,1);
numNans = numElems*0.1; % Number of NaNs is 10%
count = 1;
while count <= numNans
% Generate random number
idx = randi(numElems);
isIdxValid = false;
if ~isnan(a(idx)) % Check if index has already been set
% Check for NaNs in consecutive locations
if idx==1 % beginning of vector
if ~isnan(a(idx+1))
isIdxValid = true;
end
elseif idx==numElems % end of vector
if ~isnan(a(idx-1))
isIdxValid = true;
end
else % middle of vector
if ~isnan(a(idx+1)) && ~isnan(a(idx-1))
isIdxValid = true;
end
end
end
% If the index is valid, set that element to NaN
if isIdxValid
a(idx) = NaN;
count = count+1;
end
end
% Display stuff at the end
a
nnz(isnan(a))

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!