Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab: Addressing multiple rows in multidimensional array

Suppose that "r" is a multidimensional array of size [N, N, M] and "tab" is a table of size [N] with values 1..N (e.g. take "tab=randperm(N)"). I'm looking for efficient way to do the following:

    c = ones(M, 1);
    for k=1:N
        c = c .* squeeze(r(tab(k),k,:));
    end

I'd like to do that in matrix notation, using prod, but didn't find a solution, as "r(tab(1:N),1:N,:)" returns an NxNxM matrix rather than N rows.

Any suggestions?

like image 375
Uri Cohen Avatar asked Apr 25 '26 19:04

Uri Cohen


1 Answers

Use sub2ind across dimensions 1, 2; bsxfun to replicate along dimension 3; and then prod:

c = prod(r(bsxfun(@plus, sub2ind([N N], tab, 1:N).', (0:M-1)*N^2))).';
like image 51
Luis Mendo Avatar answered Apr 27 '26 10:04

Luis Mendo