动态创建d维张量 [英] Create a d-dimensional tensor dynamically

查看:57
本文介绍了动态创建d维张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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 = 2r = 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆