Anonymous
Anonymous

Reputation: 167

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

How to build nested array of 1x3 vectors in the (n,m) posision of 2D matrix in a for loop?

And then how to access the n,m vector ?

Is there a better way than below.

  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

Upvotes: 1

Views: 62

Answers (1)

Divakar
Divakar

Reputation: 221614

You can use ndgrid and some re-arrangement later on with reshape + permute to get the desired output -

%// 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,[])

Or you can use meshgrid there (thanks to comments by @horchler) for a compact code -

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

Upvotes: 1

Related Questions