[英]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.