How Can I randomly select 10% of my array values and replace it with N/A or zero

Hello Everyone, I hope you are doing well.
I have the dataset 250x1000 attached below. i want to randomly select 10% of element from may array and replace it with N/A or zero. How can i do that in matlab
Any help appreciated :)

 Accepted Answer

Let A be your 250x1000 array.
N = numel(A) ; % total number of elements
idx = randsample(N,round(10/100*N)) ; % select 10% of indices randomly
A(idx) = 0; % replace with 0

6 Comments

@KSSV and what about N/A? How can i replace with N/A
and if i want to get 15% where i can change
N/A is NaN you mean?
To have 15% change thi line:
idx = randsample(N,round(10/100*N)) ; % select 10% of indices randomly
@KSSV yeh i means NAN Who can i replace NAN instead of zero?
@KSSV What is different between randperm and randsample command?
It is straight forward, use NaN instead of zeros. Simple.
A(idx) = NaN ; % replace with NaN
Read doc, runt he function and you can see the difference.

Sign in to comment.

More Answers (0)

Products

Release

R2021b

Asked:

on 26 Feb 2022

Commented:

on 26 Feb 2022

Community Treasure Hunt

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

Start Hunting!