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

조회 수: 6 (최근 30일)
Rebecca Johnson
Rebecca Johnson 2017년 7월 14일
댓글: Rebecca Johnson 2017년 7월 14일
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