您可以使用累加数组 https://www.mathworks.com/help/matlab/ref/accumarray.html:
f = @(d,r)accumarray(repmat((1:r).',1 , d), 1);
> f(2,5)
=
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
这是accumarray 的基本签名:
accumarray( subs , val )
Using accumarray
我们可以创建一个 n 维数组,其中subs
表示将在数组中填充的点的位置val
代表了他们的价值。
If subs
作为矩阵提供,其列数决定了结果数组的维数,每行代表每个点的位置。
例如对于d = 2
and r = 5
我们想创建一个(5 x 5)
在以下位置有 1 的数组:[1 1],[2 2],[3 3],[4 4],[5 5]
.
Using repmat
我们可以创造subs
:
subs = repmat ((1:5).' , 1, 2)
=
1 1
2 2
3 3
4 4
5 5
val
被设定为1
所以所有指定的职位都将由1
.
. https://codegolf.stackexchange.com/questions/127904/n-dimensional-identity-matrix/127916#127916