Path: news.mathworks.com!not-for-mail
From: "helper " <spamless@nospam.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: multidimensional indexing
Date: Tue, 13 May 2008 12:30:20 +0000 (UTC)
Organization: Timothy S. Farajian, Inc.
Lines: 69
Message-ID: <g0c1ks$j83$1@fred.mathworks.com>
References: <g0b6eb$18j$1@fred.mathworks.com> <g0bigi$cp3$1@fred.mathworks.com>
Reply-To: "helper " <spamless@nospam.com>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1210681820 19715 172.30.248.35 (13 May 2008 12:30:20 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 13 May 2008 12:30:20 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1272923
Xref: news.mathworks.com comp.soft-sys.matlab:468127


"us " <us@neurol.unizh.ch> wrote in message <g0bigi$cp3
$1@fred.mathworks.com>...
> "Darius ":
> <SNIP repeating his/her ND-diag...
> 
> one of the many solutions
> 
> % the data
>      m=reshape(1:27,[3,3,3])
> % the engine
>      r=ones(3,1)*arrayfun(@(x) m(x,x,x),1:3)
> %{
>      r=
>      1 14 27
>      1 14 27
>      1 14 27
> %}
> 
> us

Ah but this doesn't quite satisfy his request which is the 
equivalent to:

r = [m(:,1,1) m(:,2,2) m(:,3,3)];

This would require the following change to your code:

r=cell2mat(arrayfun(@(x) m(:,x,x),1:3,'uni',false));

And, of course the comparison between the methods (and an 
additional one using FOR-loops):

% The data
N = 100;
m = rand(N,N,N);
t = {'helper'; 'us'; 'FOR-loops'};

% The tests
tic
for n = 1:1000
i = repmat((1:size(m,1)),size(m,1),1);
I = sub2ind(size(m),i.',i,i);
r = m(I);
end
t{1,2} = toc;

tic
for n = 1:1000
r = cell2mat(arrayfun(@(x) m(:,x,x),1:3,'uni',false));
end
t{2,2} = toc;

tic
for n = 1:1000
  r = zeros(N,N);
  for j = 1:N
    r(:,j) = m(:,j,j);
  end
end
t{3,2} = toc;

disp(t)

    'helper'       [1.1061]
    'us'           [0.5106]
    'FOR-loops'    [0.2666] % The winner


FOR-loops win again!