2
votes

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?

4
You can just multiply the matrices, without any loops.Adiel
@Adiel - it's actually right. But it would require a zero-one matrix, like stated in the question. The question title says non-zero values, which would require the transformation to logical first. It's not entirely clear. But for the first case, your approach is a little faster.Robert Seifert
Actually you right, but i took only the case in the question, didn't notice the difference in the title. But, he says that's the matrix he has... :)Adiel

4 Answers

4
votes

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)

4
votes

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));
3
votes

If you're trying to replace the ones in matrix A with random numbers then you don't need any looping at all.

Here's one method.

a = double(rand(5,5)>.5); % Your binary matrix should be type double.
n = sum(a(:));            % Count the 1's.
a(a>0) = rand(1,n);       % Replace the ones with rands. 
0
votes

If 'l' is a matrix containing zeros and non-zeros. Consider the scenarios below answering this question :

  1. Replace all the zeros in matrix with random numbers :

    l(l==0) = randn(1,size(l(l==0),1)); 
    
  2. Replace all the positive values with random numbers :

    l(l>0) = randn(1,size(l(l>0),1));
    
  3. Replace all the negative values with random numbers :

    l(l<0) = randn(1,size(l(l<0),1));
    
  4. Replace all the 'NaN' with random numbers.

    l(isnan(l)) = randn(1,size(l(isnan(l)),1));