help-octave
[Top][All Lists]
Advanced

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

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

 From: Andy Buckle Subject: Re: efficiently modifying a 0-1 matrix for a fixed row sum Date: Tue, 7 Sep 2010 16:18:37 +0100

```On Tue, Sep 7, 2010 at 4:35 AM, 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.
>

This does use a loop...

The number of iterations seems to be independent of the length of the
vector (but I have not scratched my head long enough over the stats to
see if that is definitely the case).

This is quite ugly code. I wait eagerly to see who can do better.

bvl=100;
reqsum=round(0.2*bvl);
printf("required sum: %i\n",reqsum);
bv=round(rand(1,bvl));
s=sum(bv);
printf("initial sum: %i\n",s);
while abs(extra=reqsum-sum(bv)) >0.1
s=sum(bv)
if extra>0.1 % need more ones
spaces=bvl-s;
ev=(rand(1,spaces)<(extra/spaces));
bv(~logical(bv))=ev;
elseif extra<-0.1% more zeros
spaces=s;
ev=(rand(1,spaces)<(-extra/spaces));
bv(logical(bv))=~ev;
end
end
s=sum(bv);
printf("final sum: %i\n",reqsum);

--
/* andy buckle */

```

reply via email to

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