Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get different columns of each row from matrix

Matrix A = [19,20,30; 41,54,65; 72,83,95]

Matrix B = [2,3; 1,3; 3,3]

Output Matrix C = [20; 30; 41; 54; 65; 95]

Matrix B includes which columns should be transferred to output matrix C. For example, second row of B is 1 and 3. So from second row of A; elements between 1st and 3rd column should be transferred to output matrix C.

Without for loop, only with matrix operations, how can I do this?

like image 654
oarar Avatar asked Dec 19 '25 14:12

oarar


1 Answers

Since you want row-major order (and Matlab works in column major order), transpose A first. Then build a logical mask to be used as index into A transposed:

At = A.'; %'
mask = (bsxfun(@ge, (1:size(At,1)), B(:,1)) & bsxfun(@le, 1:size(At,1), B(:,2))).'; %'
result = At(mask);
like image 72
Luis Mendo Avatar answered Dec 22 '25 14:12

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!