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

4 次查看(过去 30 天)
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!

回答(1 个)

Sebastian Castro
Sebastian Castro 2017-7-14
编辑:Sebastian Castro 2017-7-14
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))

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by