Home > OS >  extracting same columns from two matrices
extracting same columns from two matrices

Time:05-11

I have matrix X which has a size (8,1500) and Y which has a matrix (2,1500). How can I extract 100 random columns from both matrices?

Meaning if I extract column 20 from matrix X, I have to do the same for matrix Y.

CodePudding user response:

So you have

X = rand(8,1500); 
Y = rand(2,1500);

You can create a random index of 100 columns and select it from both matrices

idx = randperm( 1500, 100 );
Xi = X(:,idx);
Yi = Y(:,idx);

Note I've used randperm to get 100 unique columns, i.e. no repeats. If you're happy to have random repeats you could replace randperm(1500,100) with randi(1500,1,100);

CodePudding user response:

Is this what you're looking for ?

A = rand( 8,1500 );
B = rand( 2,1500 );

ncol = 100;
cols = ceil( rand( ncol, 1 ) * 1500 );

Ac = zeros( 8, ncol );
Bc = zeros( 2, ncol );
for pos = 1:ncol
    col = cols(pos);
    Ac(:,pos) = A(:,col);
    Bc(:,pos) = B(:,col);
end

Ac(:,1)
A(:,cols(1))

You generate a random list of column number, between 1 and 1500. And take the same position from A and B.

  • Related