SJL
SJL

Reputation: 39

How to randomly replace 10% of elements in a matrix into zero

Let C be a 40x40 matrix with zeros in the diagonal. How do I randomly replace 10% of the elements in the matrix with zeros?

Upvotes: 2

Views: 2431

Answers (3)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

I think the fastest method would be to use logical indexing in combination with scalar assignment:

C(rand(size(C)) < 0.1) = 0;

but that would not give you exactly 10% as you specified.

An exact solution is

nC = numel(C);
[~, p] = sort(rand(1, nC));
C(p <= nC/10) = 0;

which is identical to randperm without the overhead of randperm() in Matlab R2010 and earlier.

Upvotes: 2

Gunther Struyf
Gunther Struyf

Reputation: 11168

Instead of @HighPerformanceMark 's mask*matrix method, I would simply index the matrix itself:

data=rand(10);

N = numel(data);
data(randperm(N,floor(N/10))) = 0;

Upvotes: 4

High Performance Mark
High Performance Mark

Reputation: 78316

For exactly 10% elements replaced by 0 something like this might satisfy you:

mask = [ones(1,1440),zeros(1,160)];
mask = reshape(mask(randperm(1600)),[40,40]);
c.*mask

If probably 10% is acceptable, try

c.*(randi(10,40)<=9)

I guess you can figure these out, if not comment.

Upvotes: 3

Related Questions