Path: news.mathworks.com!newsfeed-00.mathworks.com!newsfeed2.dallas1.level3.net!news.level3.com!postnews.google.com!news1.google.com!border1.nntp.dca.giganews.com!nntp.giganews.com!npeer02.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!post01.iad.highwinds-media.com!newsfe01.iad.POSTED!7564ea0f!not-for-mail
From: Walter Roberson <roberson@hushmail.com>
Organization: Canada Eat The Cookie Foundation
User-Agent: Thunderbird 2.0.0.17 (Windows/20080914)
MIME-Version: 1.0
Newsgroups: comp.soft-sys.matlab
Subject: Re: Random matrix with zeros and ones and twos
References: <7946648.1226342494201.JavaMail.jakarta@nitrogen.mathforum.org>
In-Reply-To: <7946648.1226342494201.JavaMail.jakarta@nitrogen.mathforum.org>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Lines: 31
Message-ID: <Nm0Sk.12$Ls1.1@newsfe01.iad>
NNTP-Posting-Host: 24.79.146.116
X-Complaints-To: internet.abuse@sjrb.ca
X-Trace: newsfe01.iad 1226347053 24.79.146.116 (Mon, 10 Nov 2008 19:57:33 UTC)
NNTP-Posting-Date: Mon, 10 Nov 2008 19:57:33 UTC
Date: Mon, 10 Nov 2008 13:57:51 -0600
Xref: news.mathworks.com comp.soft-sys.matlab:500060


Tim Smith wrote:
> I need to create a 100 x 100 matrix filled 80% with zeros, 10% with ones and 10% twos.
> The distribution should be random.

Should it be -exactly- 10% ones and -exactly- 10% twos? Or are those the means
and there is a probability distribution for how they occur? For example, is the
rule that for any given location, the content of the location is a uniform
random distribution, 0.8 zero, 0.1 one, 0.l two? That's a quite different
situation than saying that 10% of the 100 x 100 should be ones.

Here is what you asked for:

TheMatrix = zeros(100,100);
Nel = numel(TheMatrix);
Rindices = randperm(Nel);
N10 = floor(Nel/10);
TheMatrix(Rindices(1:N10)) = 1;
TheMatrix(Rindices(N10+1:N10+N10)) = 2;

(Yes, there are more efficient ways, but the above is easily vectorized.
In particular, you don't need to generate as many random numbers as there are
elements in the full vector -- but you do want to ensure that they are -unique-
element subscripts that you generate, and selection without replacement
implemented as "selection with replacement and reject duplicates" has an
indefinite wait time.)

-- 
.signature note: I am now avoiding replying to unclear or ambiguous postings.
Please review questions before posting them. Be specific. Use examples of what you mean,
of what you don't mean. Specify boundary conditions, and data classes and value
relationships -- what if we scrambled your data or used -Inf, NaN, or complex(rand,rand)?