繁体   English   中英

如何在MATLAb中的2D矩阵的n,m位置构建1x3向量的嵌套数组?

[英]How to build nested array of 1x3 vectors in the n,m posision of 2D matrix in MATLAb?

如何在for循环中的2D矩阵的(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和一些重新排列以及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使用meshgrid (感谢@horchler的评论)以编写紧凑的代码-

[X,Y] = meshgrid(1:n,1:m); 
A = reshape(permute(reshape([X(:).';Y(:).';X(:).'],3,m,[]),[1 3 2]),n*3,[])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM