matlabmatrix

N-dimensional identity tensor in MATLAB


The function eye does not support N-dimensional arrays.

I would like to create a matrix such that

I(i,j,:,:) = eye(3,3)

in a vectorial fashion, without having to loop over i and j.

What is the best way to do this? I haven't been able to find anything in the documentation.


Solution

  • You can use repmat to repeat eye into the 3rd and 4th dimensions, and use shiftdim to shift the dimensions

    % for i = 1 to M, and j = 1 to N
    k = shiftdim( repmat( eye(3,3), 1, 1, M, N ), 2 );
    

    The output is nasty, because MATLAB doesn't display >2D data very well, but here are a couple of tests:

    % Test that a given i-j pair gives eye(3,3) in the 3rd and 4th dimension
    isequal( k(1,2,:,:), reshape( eye(3,3), 1, 1, 3, 3 ) ); % = 1, passed
    % Test I-j slices are equal and i/j are oriented correctly. Test with M ~= N
    isequal( k( 1, 1, :, : ), k( M, N, :, : ) ); %  = 1, passed
    

    And here is the actual output of a slice

    % Below is equivalent to eye(3,3) in the 3rd and 4th dimensions
    k(3,4,:,:)
    ans(:,:,1,1) =
         1
    ans(:,:,2,1) =
         0
    ans(:,:,3,1) =
         0
    ans(:,:,1,2) =
         0
    ans(:,:,2,2) =
         1
    ans(:,:,3,2) =
         0
    ans(:,:,1,3) =
         0
    ans(:,:,2,3) =
         0
    ans(:,:,3,3) =
         1