Indice wise reference of indice from another matrix

1 view (last 30 days)
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.
  4 Comments
Valerian Cinçon
Valerian Cinçon on 25 Mar 2019
>> A= [0 1 ; 1 1];
matrice_delay = [1 1 ; 2 3];
A_delayed = zeros (2,2,3);
for i10=1:2
for i11=1:2
A_delayed(i10,i11,matrice_delay(i10,i11))=A(i10,i11);
end
end
>> A_delayed
A_delayed(:,:,1) =
0 1
0 0
A_delayed(:,:,2) =
0 0
1 0
A_delayed(:,:,3) =
0 0
0 1

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 25 Mar 2019
Edited: Stephen23 on 25 Mar 2019
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
  1 Comment
Valerian Cinçon
Valerian Cinçon on 25 Mar 2019
Dear Stephen,
Thank you for your wonderful contribution.
Best regards,
Valérian,

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!