动态创建d维张量 [英] Create a d-dimensional tensor dynamically
问题描述
我想使用d
作为输入并不使用if
语句创建d维张量:
I would like to create a d-dimensional tensor using d
as an input and without the if
statement as below:
if d == 2
B = zeros(r,r);
for i = 1:r
B(i,i) = 1;
end
elseif d == 3
B = zeros(r,r,r);
for i = 1:r
B(i,i,i) = 1;
end
end
有没有更有效的方法?
推荐答案
您可以使用这是accumarray的基本特征:
Here is the basic signature of accumarray:
accumarray( subs , val )
使用accumarray
,我们可以创建一个n维数组,其中subs
表示将要填充的点的位置,而val
表示它们的值.
Using accumarray
we can create an n-dimensional array where subs
represents the position of points that will be filled in the array and val
represents the value of them.
如果subs
作为矩阵提供,则其列数确定所得数组的维数,并且每一行代表每个点的位置.
If subs
provided as a matrix , its number of columns determines the number of dimensions of the resultant array and each row represents position of each point.
例如对于d = 2
和r = 5
,我们要创建一个在以下位置具有1s的(5 x 5)
数组:[1 1],[2 2],[3 3],[4 4],[5 5]
.
For example for d = 2
and r = 5
we want to create a (5 x 5)
array that has 1s in the following positions: [1 1],[2 2],[3 3],[4 4],[5 5]
.
使用repmat
我们可以创建subs
:
subs = repmat ((1:5).' , 1, 2)
=
1 1
2 2
3 3
4 4
5 5
val
设置为1
,因此所有指定位置将由1
填充.
val
is set to 1
so all specified positions will be filled by 1
.
这篇关于动态创建d维张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!