如何在 MATLAb 中的二维矩阵的 n、m 位置构建 1x3 向量的嵌套数组?
How to build nested array of 1x3 vectors in the n,m posision of 2D matrix in MATLAb?
如何在 for 循环中的二维矩阵的 (n,m) 位置构建嵌套的 1x3 向量数组?
然后如何访问 n,m 向量?
有没有比下面更好的方法呢
for n =1:2
for m =1:3
v = [n,m,n]' % test vector to be stored
A(3*n-2:3*n,m) = v;%
end
end
n =2; m=3;
v = A(3*n-2:3*n,m); % get vector at n,m position
A
v
您可以使用 ndgrid
and some re-arrangement later on with reshape
+ permute
来获得所需的输出 -
%// Get the vector v values which are rectangular grid data on a 2D space
[X,Y] = ndgrid(1:n,1:m)
%// Reshape those values and re-arrange into a 2D array as the final output
X1 = reshape(X.',1,[]) %//'
Y1 = reshape(Y.',1,[]) %//'
A = reshape(permute(reshape([X1 ; Y1 ; X1],3,m,[]),[1 3 2]),n*3,[])
或者您可以在那里使用 meshgrid
(感谢@horchler 的评论)以获得紧凑的代码 -
[X,Y] = meshgrid(1:n,1:m);
A = reshape(permute(reshape([X(:).';Y(:).';X(:).'],3,m,[]),[1 3 2]),n*3,[])
如何在 for 循环中的二维矩阵的 (n,m) 位置构建嵌套的 1x3 向量数组?
然后如何访问 n,m 向量?
有没有比下面更好的方法呢
for n =1:2
for m =1:3
v = [n,m,n]' % test vector to be stored
A(3*n-2:3*n,m) = v;%
end
end
n =2; m=3;
v = A(3*n-2:3*n,m); % get vector at n,m position
A
v
您可以使用 ndgrid
and some re-arrangement later on with reshape
+ permute
来获得所需的输出 -
%// Get the vector v values which are rectangular grid data on a 2D space
[X,Y] = ndgrid(1:n,1:m)
%// Reshape those values and re-arrange into a 2D array as the final output
X1 = reshape(X.',1,[]) %//'
Y1 = reshape(Y.',1,[]) %//'
A = reshape(permute(reshape([X1 ; Y1 ; X1],3,m,[]),[1 3 2]),n*3,[])
或者您可以在那里使用 meshgrid
(感谢@horchler 的评论)以获得紧凑的代码 -
[X,Y] = meshgrid(1:n,1:m);
A = reshape(permute(reshape([X(:).';Y(:).';X(:).'],3,m,[]),[1 3 2]),n*3,[])