Matlab中的N维身份张量

时间:2019-02-20 15:59:19

标签: matlab matrix

函数eye不支持N维数组。

我想创建一个矩阵

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

以矢量的方式,而不必循环ij

做到这一点的最佳方法是什么?我在文档中找不到任何东西。

1 个答案:

答案 0 :(得分:1)

您可以使用repmateye重复到第3维和第4维,并使用shiftdim来移动尺寸

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

输出令人讨厌,因为MATLAB无法很好地显示> 2D数据,但是这里有一些测试:

% 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

这是切片的实际输出

% 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