Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace non-zero values with random numbers

Tags:

matrix

matlab

I have a zero-one matrix in MATLAB as follows:

[0 0 0 1 1 1
 0 1 1 0 0 0
 1 0 0 0 0 1
 1 1 1 0 0 0
 0 0 0 1 0 1]

I want to define another matrix including rand values instead of indexes of above matrix by 1. For instance the desired new rand matrix should be:

[0 0 0 0.2 0.2 0.1
 0 0.6 0.7 0 0 0
 0.4 0 0 0 0 0.6
 0.7 0.8 0.5 0 0 0
 0 0 0 0.3 0 0.4]

I used a two nested loop for to find non-zero values from first matrix and replace the rand values instead of them in a new matrix.

Is there any function of matlab to do it automatically, without using two nested loop for?

like image 613
BlueBit Avatar asked May 23 '26 16:05

BlueBit


2 Answers

You can do it as follows:

A = ...
[0 0 0 1 1 1;
 0 1 1 0 0 0;
 1 0 0 0 0 1;
 1 1 1 0 0 0;
 0 0 0 1 0 1];

B = rand(size(A));
A(logical(A)) = B(logical(A));

A =

         0         0         0    0.1320    0.2348    0.1690
         0    0.3377    0.3897         0         0         0
    0.9027         0         0         0         0    0.7317
    0.9448    0.3692    0.4039         0         0         0
         0         0         0    0.0598         0    0.4509

(I just took the basic rand-function, adjust it, as you need it)

like image 197
Robert Seifert Avatar answered May 25 '26 08:05

Robert Seifert


You can slightly improve thewaywewalk's answer by generating only as many random numbers as you need. As a bonus, this approach allows to do everything in one line:

A(logical(A)) = rand(1,nnz(A));
like image 41
Luis Mendo Avatar answered May 25 '26 07:05

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!