help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Fwd: efficiently modifying a 0-1 matrix for a fixed row sum


From: Moo
Subject: Fwd: efficiently modifying a 0-1 matrix for a fixed row sum
Date: Tue, 7 Sep 2010 10:28:04 -0600

---------- Forwarded message ----------
From: Moo <address@hidden>
Date: Tue, Sep 7, 2010 at 10:24 AM
Subject: Re: efficiently modifying a 0-1 matrix for a fixed row sum
To: address@hidden


On Mon, Sep 6, 2010 at 9:35 PM, Mike B. <address@hidden> wrote:
Hi All,

I have a matrix of 0-1 elements which are randomly distributed.

I need to modify the matrix such that each row has exacly the same sum, for example, assuming the target sum is 2 and the initial matrix is
0 1 0 (sum=0, too low)
1 1 1 (sum=3, too high)

one possible outcome is
1 1 0 (sum=2)
1 0 1 (sum=2)

Any way to avoid slow for loops?.

Thanks,
Mike.


When you say "modify" the original matrix you make what you're doing ambiguous to me.  Are you aiming for the distribution of 1s in your matrix to obey a certain probability distribution (e.g. uniform)? Do you need to keep some special properties of your original A matrix? If this is the case, you'll probably have to give more information about what you're trying to do.

Or if you do not really care, and just want a random matrix with constant rowsum, then it'd be easier to do by scratch.  This uses one for loop (once for each row), but this can be removed if someone else knows how to call the same function (randperm) multiple times without a for loop.  This method is a bit wasteful too, since I need to make n random numbers but only use (k/n) of them on each for loop.

%-----

n = 100;  %size of matrix
k = 10;    %prescribed row sum

A = spalloc(n,n, k*n);    %you can use A=zeros(n) here instead, if you like
v = zeros(1,n);

for i = 1:n
    v = randperm(n);
    A(i,v(1:k)) = 1;
end

sum(A,2)  %check that the row sums == k.

%-----

(i forgot to reply to all)

reply via email to

[Prev in Thread] Current Thread [Next in Thread]