Qiang Li
Qiang Li

Reputation: 10855

How can I generate this 3-D matrix without for loops in MATLAB?

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

Answers (3)

Amro
Amro

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

Jonas
Jonas

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

gnovice
gnovice

Reputation: 125864

One way to do this is to use the functions KRON and RESHAPE:

>> N = 4;
>> A = reshape(kron(1:3,eye(N)),[N N 3])

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: 1

Related Questions