Replacing Set Number of Random rows with a value

I have a 1-D numeric matrix (10000x1 double). I would like to select a random 8000 of the entries and replace them with the value "i" while still maintaning the same order.
For instance, if the matrix only had 10 values [1, 5, 8, 3, 7, 3, 7, 2, 4, 3] and I want to replace 8 out of 10 randomly with the number 13, so that the result would be something like [13, 13, 13, 13, 7, 13, 13, 13, 13, 3] or [1, 13, 8, 13, 13, 13, 13, 13, 13, 13]. How would I go about doing this?

Answers (1)

Use randperm( ) to generate the random indexes, and then just use these indexes in an assignment.

2 Comments

thanks so much for the quick reply!
i entered
idx = randperm(10000,2000);
matrix(idx) = 13;
and it worked great!
however, is there a nifty way to have it write into a new separate matrix so the original doesn't get overwritten?
Just copy matrix first. E.g.,
new_matrix = matrix;
idx = randperm(10000,2000);
new_matrix(idx) = 13;

Sign in to comment.

Asked:

on 12 Nov 2020

Commented:

on 12 Nov 2020

Community Treasure Hunt

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

Start Hunting!