Another option is to use BSXFUN , multiplying the identifier matrix by a 1-by-3 array of1,2,3
>> bsxfun(@times,eye(4),permute(1:3,[3,1,2]))
ans(:,:,1) =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
ans(:,:,2) =
2 0 0 0
0 2 0 0
0 0 2 0
0 0 0 2
ans(:,:,3) =
3 0 0 0
0 3 0 0
0 0 3 0
0 0 0 3
Jonas source
share