Path: news.mathworks.com!newsfeed-00.mathworks.com!news.kjsl.com!newsfeed.stanford.edu!newsfeed.news.ucla.edu!nrc-news.nrc.ca!newsflash.concordia.ca!canopus.cc.umanitoba.ca!not-for-mail
From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Newsgroups: comp.soft-sys.matlab
Subject: Re: density matrix conversion - vectorization
Date: Fri, 1 Aug 2008 17:36:52 +0000 (UTC)
Organization: National Research Council Canada - Conseil national de rechereches Canada
Lines: 57
Message-ID: <g6vhjk$6m4$1@canopus.cc.umanitoba.ca>
References: <g6v9mp$g0r$1@news.dialog.net.pl> <g6vbjk$rbn$1@canopus.cc.umanitoba.ca> <g6vcmb$hqn$1@news.dialog.net.pl>
NNTP-Posting-Host: origin.ibd.nrc.ca
X-Trace: canopus.cc.umanitoba.ca 1217612212 6852 192.70.172.160 (1 Aug 2008 17:36:52 GMT)
X-Complaints-To: abuse@cc.umanitoba.ca
NNTP-Posting-Date: Fri, 1 Aug 2008 17:36:52 +0000 (UTC)
Originator: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Xref: news.mathworks.com comp.soft-sys.matlab:483169



In article <g6vcmb$hqn$1@news.dialog.net.pl>, uC <bla.bla@uc.uc> wrote:

>sorry for that. ok, the entity is a human, ane the MxN matrix is population 
>density (one matrix element represents 25x25 meters pixel). so, form MxN 
>matrix I would like to generate "real" people with their locations being 
>randomly distributed within each 25x25 pixel

Presuming that the density matrix (call it D) contains counts 
rather than probabilities:

P = sum(D(:));          %total population
randpos = rand(P,2);
rawx = randpos(:,1);
rawy = randpos(:,2);
groupedx = reshape(mat2cell(rawx,D(:)), size(D));
groupedy = reshape(mat2cell(rawy,D(:)), size(D));

Then for each entry D(Q,R), groupedx{Q,R} are the x coordinates
and groupedy{Q,R} are the y coordinates, each cell relative.

If you need to convert to absolute coordinates:

[coloff,rowoff] = meshgrid(0:size(D,2)-1,0:size(D,1)-1);
absx = cellfun(@(c,d) c+d, groupedx, num2cell(rowoff), 'Uniform', 0);
absy = cellfun(@(c,d) c+d, groupedy, num2cell(coloff), 'Uniform', 0);

And if you need to,

xypairs = cellfun(@(c,d) [c,d], absx, absy, 'Uniform',0);

For example, with D = [3 0 5;9 1 2] this produced
xypairs = 

    [3x2 double]    [0x2  double]    [5x2 double]
    [9x2 double]    [1x2 double]    [2x2 double]

and for this run,

>> xypairs{2,3}

          1.26297128454014          2.08443584551091
          1.65407909847678           2.3997826490989


Cross check:

allxy = cat(1,xypairs{:});
scatter(allxy(:,1),allxy(:,2));


Note: it might turn out to be faster to use a loop for the
conversion to absolute coordinates and forming the xy pairs.
You could do it as a single loop over 1:numels(D)
-- 
  "The human mind is so strangely capricious, that, when freed from
  the pressure of real misery, it becomes open and sensitive to the
  ideal apprehension of ideal calamities."          -- Sir Walter Scott