MATLAB: Replace a Fraction of numerical Values with NaN excluding already existing NaN in the Matrix

I am simulating resistance of my theoretical model against missing data and for that reason want to randomly set a specified fraction (e.g. 20%) of all numerical values in a 2 dimensional matrix (approx. 200×10000) to NaN. The matrix already has NaN cells (with no particular distribution in the original Matrix) due to the nature of the input format (so NOT representing missing data) that I would like to exclude from calculation for that process.
I would like to be able to set that fraction accurately, so calculating the total fraction of NaN already in the matrix before and increasing the fraction later used by the random generator doesn't work as a simple workaround.
Is there a process I could use to achieve this? Thanks!

Best Answer

Does this do what you want? Sets fraction of current non-NaN values to NaN:
x = your matrix
frac = 0.20; % Fraction of current non-NaN's to set to NaN
f = find(~isnan(x)); % The non-NaN locations
n = numel(f); % Number of non-NaN locations
r = randperm(n,floor(frac*n)); % Randomly pick frac of these non-NaN locations
x(f(r)) = NaN; % Set the new locations to NaN
If frac was supposed to apply to the total number of elements of x and not the total number of non-NaN elements of x, then make this adjustment:
r = randperm(n,min(n,floor(frac*numel(x)))); % Randomly pick frac of these locations