[英]Generate a 3-d matrix from a vector in Matlab
I have a vector A
in Matlab of dimension (N-1)x1
我在Matlab中有一个向量
A
(N-1)x1
A=[0:1:N-2]'
with N>=3
, eg with N=4 A=[0 1 2]
N>=3
,例如N=4 A=[0 1 2]
I want to construct a 3-dimensional matrix B
of dimension Mx(N-1)x(N-1)
without using loops such that eg with N=4
, M=5
我想构造一个尺寸为
Mx(N-1)x(N-1)
的3维矩阵B
,而无需使用循环,例如N=4
, M=5
B(:,:,1)=[0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0]
B(:,:,2)=[1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1]
... ...
B(:,:,end)=[N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2;
N-2 N-2 N-2 N-2]
Here's one approach with kron
and reshape
: 这是使用
kron
和reshape
的一种方法:
A = 0:N-2;
B = reshape(kron(A, ones(M, N-1)), M, N-1, []);
We use kron
to produce M x (N-1)
2D matrices that are stacked for as many elements as there are in A
and each matrix is multiplied by the corresponding value in A
. 我们使用
kron
产生M x (N-1)
被堆叠为尽可能多的元件,因为有在二维矩阵A
并且每个矩阵是通过在对应的值相乘A
。 The next step is to take each of the concatenated 2D matrices and place them as individual slices in the third dimension, done by reshape
. 下一步是获取每个串联的2D矩阵,并将它们作为单独的切片放置在三维中,并通过
reshape
完成。
M = 5, N = 4
M = 5, N = 4
示例 >> B
B(:,:,1) =
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
B(:,:,2) =
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
B(:,:,3) =
2 2 2
2 2 2
2 2 2
2 2 2
2 2 2
Is this what you want? 这是你想要的吗?
B = repmat(reshape(A,1,1,[]), M, N-1); %// or change N-1 to N, according to your example
Another possibility: 另一种可能性:
B = bsxfun(@times, reshape(A,1,1,[]), ones(M, N-1)); %// or change N-1 to N
Yet another: 完后还有:
B = reshape(A(ceil((1:numel(A)*M*(N-1))/M/(N-1))), M, N-1, []); %// or change N-1 to N
我将继续使用permute
直到掌握了...
B = ones(M,N-1,N-1).*permute(A,[3,2,1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.