MATLAB: Indice wise reference of indice from another matrix

matrix manipulationmatrix wise indexing

I search a better writing (without for loop) than the following functionning code.
the code write on the 3rd dimmension of A_delayed wisely to an indice stored in a separate matrice.
For each row,colum of A the 3rd dimmension indice can be different.
for i10=1:row_A
for i11=1:colum_A
A_delayed(i10,i11,matrice_delay(i10,i11))=A(i10,i11);
end
end
Thank in advance.

Best Answer

Use ndgrid and sub2ind:
>> A = [0,1;1,1];
>> D = [1,1;2,3];
>> B = zeros(2,2,3);
>> S = size(B);
>> [R,C] = ndgrid(1:S(1),1:S(2));
>> B(sub2ind(S,R,C,D)) = A
B(:,:,1) =
0 1
0 0
B(:,:,2) =
0 0
1 0
B(:,:,3) =
0 0
0 1