Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

Suppose I have a matrix $A$ of size

$n_1 \times n_2 \times n_3$

Now, I have another matrix $B$ of size $n_1 \times n_2 \times N$ where $N<n_3$

I'd like to create the following matrix $C = [A(m,l,B(m,l,:))]_{1 \le m \le n_1, 1 \le l \le n_2}$, whch has the same size as $B$. What is the most efficient way of doing this without having to create loops?

share|improve this question
    
If you have three dimensions, then it isn't really a matrix anymore; it's a rank-3 tensor. –  J. M. Jul 9 '12 at 17:32
    
what does $B(m,l)$ mean if $B$ is a 3D array? –  chaohuang Jul 9 '12 at 18:00
2  
This is for mathworks.com/matlabcentral/answers. –  Dirk Jul 9 '12 at 18:14
    
sorry i should be $B(m,l,:)$, It's basically a vector of size $N$. Thanks –  Stuck_pls_help Jul 9 '12 at 18:48
    
When it comes to issues like efficiency of numerical algorithms, you may consider asking instead at scicomp.stackexchange.com –  Willie Wong Jul 10 '12 at 6:34
add comment

closed as off-topic by Shobhit, azimut, Dennis Gulko, amWhy, Norbert Oct 29 '13 at 18:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question is not about mathematics, within the scope defined in the help center." – Shobhit, azimut, Dennis Gulko, amWhy, Norbert
If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 2 down vote accepted
C = A(repmat(reshape(1:n1*n2,n1,n2),[1,1,N])+(n1*n2)*(B-1));
share|improve this answer
    
This doesn't work. This yields a matrix that may be nonpoistive: repmat(reshape(1:n1*n2,n1,n2),[1,1,N])+(n1*n2)*(B-1). @p.s. –  Stuck_pls_help Jul 25 '12 at 22:05
    
The formula assumes that the elements of B are in the range $[1,n_3]$ not $[0,n_3-1]$. –  p.s. Jul 25 '12 at 23:22
    
Got it. Sorry. I was confusing myself. This is great. Thanks @p.s. –  Stuck_pls_help Jul 26 '12 at 3:28
    
Do you have any suggestions if I wanted to create another matrix of the following form: $C = [A(m,l,B(m,l,n,:),n)]_{1 \le m \le n_1, 1 \le l \le n_2, 1 n\le n_3}$ and $B$ is an $n_1 \times n_2 \times n_3 \times N<n_3$ –  Stuck_pls_help Jul 26 '12 at 3:29
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.