开发者

Set elements of matrix to zero with probability using MATLAB

开发者 https://www.devze.com 2023-04-11 16:34 出处:网络
I have a matrix A of size mXn and I would like to set some of it elements to zero depending on the following criteria:

I have a matrix A of size mXn and I would like to set some of it elements to zero depending on the following criteria: I go through each element of the matrix开发者_StackOverflow and flip a coin whose probability of success is 0.3, if there is a success I set the element to zero else I move on to the next element. I wish to do this is MATLAB and also have the indices of elements that were changed using the above criteria. I tried using the following:

B = (rand(size(A)) <= 0.3);

I am not sure how to enable this in matrix A itself.


Or simply:

A( rand( size(A) ) < 0.3 ) = 0;


I think what you want is

I = (rand(size(A)) < 0.3);
A(I) = 0;

But I may have misunderstood the question.


First search for items that match your condition

zero_index = find( rand( size( A ) ) <= 0.3 ) );

Replace those items by zero

A( zero_index ) = zeros( size( zero_index ) )
0

精彩评论

暂无评论...
验证码 换一张
取 消