Matlab:从k张量列表创建(k + 1)张量 [英] Matlab: creating a (k+1)-tensor from a list of k-tensors
问题描述
假设您得到了一堆k张量,为简单起见,我们假设它们是2张量/矩阵:
Assume you are given a bunch of k-tensors, for simplicity let's say they are 2-tensors/matrices:
X = rand(5,5); Y = rand(5,5);
是否存在将它们组合成3张量的惯用法,其中第一个维度索引矩阵?一种方法是
Is there an idiom for combining them into a 3-tensor, where the first dimension indexes the matrix? One way to do it is
P(1,:,:) = X;
P(2,:,:) = Y;
,现在P根据需要具有尺寸2x5x5
.有一个更好的方法吗?
例如,在numpy中,只需输入:
and now P has dimensions 2x5x5
as required. Is there a better way to do this?
For example, in numpy one could simply type:
P = array((X,Y))
,但是在matlab中键入P=[X Y]
或P=[X; Y]
会分别给出10x5
和5x10
矩阵,而不是预期的2x5x5
.
but in matlab typing P=[X Y]
or P=[X; Y]
would give 10x5
and 5x10
matrices respectively rather than the intended 2x5x5
.
推荐答案
使用 cat
命令.
假设您有5个大小为(x,y,z)
的矩阵
Suppose you have 5 matrices of size (x,y,z)
,
A = rand(x,y,z); B = rand(x,y,z); C = rand(x,y,z); D = rand(x,y,z); E = rand(x,y,z);
串联的矩阵将是
M = cat(4, A, B, C, D, E);
其中,4
是第4维.输出M
的大小为(x,y,z,5)
.在MATLAB中,每个矩阵A,B,...
的大小为(x,y,z,1,1,...)
,即它们的第4维长度为1.
where 4
refers to the 4-th dimension. The output M
has size (x,y,z,5)
. In MATLAB, each of the matrices A,B,...
has a size of (x,y,z,1,1,...)
, i.e. their 4-th dimensional length is 1.
在连接之后,可能有必要更改维度索引的顺序,以便第一个维度是新创建的维度.使用 permute
命令.
After the concatenation, it might be necessary to change the order of dimensional indices so that the first dimension is the newly-created dimension. Use the permute
command.
N = permute(M, [4, 1, 2, 3]);
输出矩阵N
的大小为(5,x,y,z)
.
编辑历史记录
Edit history
- 将输入矩阵的大小从
(3,3,3)
更改为(x,y,z)
,以在区分和排列时清楚地区分每个维度. - 添加了
permute
,这是满足OP的尺寸索引要求所必需的.
- Changed input matrix size from
(3,3,3)
to(x,y,z)
to clearly distinguish each dimension during concatenation and permutation. - Added
permute
, which was necessary in order to satisfy OP's dimensional index requirement.
这篇关于Matlab:从k张量列表创建(k + 1)张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!