How can I generate this three-dimensional matrix without loops in MATLAB?

I would like to create an N-by-N-by-3 matrix Asuch that A(:,:,i) = eye(n)*i. How can I do this without using for loops (i.e. in vector form)?

+3
source share
3 answers

If you have an older version of MATLAB installed before BSXFUN appears, consider this option (same answer as @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
0
source

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

>> 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
+1
source

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
+1
source

Source: https://habr.com/ru/post/1779262/


All Articles