Get different columns of each row from a 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]

The matrix B

includes which columns should be wrapped in the output matrix C

. For example, the second line B

is equal to 1

and 3

. So from the second line A

; the elements between the 1st and 3rd columns must be mapped to the output matrix C

.

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

+3


source to share


1 answer


Since you want row order (and Matlab works in basic column order), transpose first A

. Then create a boolean mask to be used as an index in the A

transpose:



At = A.'; %'
mask = (bsxfun(@ge, (1:size(At,1)), B(:,1)) & bsxfun(@le, 1:size(At,1), B(:,2))).'; %'
result = At(mask);

      

+3


source







All Articles