Reputation: 10855
I'd like to generate an N-by-N-by-3 matrix A
such that A(:,:,i) = eye(n)*i
. How can I do this without using for loops (i.e. in a vectorized fashion)?
Upvotes: 3
Views: 339
Reputation: 124563
If you have an older version of MATLAB before BSXFUN was introduced, consider this option (the same answer as the one by @Jonas):
N = 4; M = 3;
A = repmat(eye(N),[1 1 M]) .* repmat(permute(1:M,[3 1 2]),[N N 1])
A(:,:,1) =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
A(:,:,2) =
2 0 0 0
0 2 0 0
0 0 2 0
0 0 0 2
A(:,:,3) =
3 0 0 0
0 3 0 0
0 0 3 0
0 0 0 3
Upvotes: 0
Reputation: 74940
Another option is to use BSXFUN, multiplying the identity matrix with a 1-by-1-by-3 array of 1,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
Upvotes: 1