Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Vectorizing Specific Access to Multidimensional Array
Date: Sun, 14 Sep 2008 06:08:03 +0000 (UTC)
Organization: Boston University
Lines: 66
Message-ID: <gai9o3$fer$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1221372483 15835 172.30.248.37 (14 Sep 2008 06:08:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 14 Sep 2008 06:08:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 844160
Xref: news.mathworks.com comp.soft-sys.matlab:490165



Let's say I have a NxMxL array X where N = M = L = 2:

X(:,:,1) = 

1 3
2 4

X(:,:,2) = 

5 7
6 8

For each vector along L ([1 5], [3 7], etc.), I want to pick a random element of it (in this case either the first or second element). One 'dumb' way of doing this is:

z = zeros(2,2,2);

for n = 1:N
     for m = 1:M
          v = floor(1 + 2 * rand(1,1));
          z(n,m,v) = 1;
     end
end

The resulting matrix z will end up looking something like, say:

z(:,:,1) = 

1 0
0 1

z(:,:,2) = 

0 1
1 0

and X .* z is

(:,:,1) = 

1 0
0 4

(:,:,2) = 

0 7
6 0

so that sum(X .* z,3) = 

1 7
6 4

Is there any way to create a random matrix z directly so that I can avoid those loops? 

Better yet, is there a way to read a random matrix R that has the elements

R = floor(1 + 2 * rand(2,2));

which might look like

1 2
2 1

that I could use to directly access elements of X, using R along the dimension L?

I realize this may be very confusing. Of course I'm happy to clarify anything I can. Thanks.