HappyPy
HappyPy

Reputation: 10697

select elements from matrix based on multiple range values

a = 1:20;
b = [2,5;12,16];

I'm looking for a way to extract the elements in a within the range of b rows. I tried

bsxfun(@(col1,col2) a(col1:col2), b(:,1), b(:,2))

but this ignores all but the first row of b.

This is the output I expect

2 3 4 5 12 13 14 15 16

Upvotes: 1

Views: 40

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4757

This bsxfun function uses the values defined within each respective row of a to create two distinct vectors and concatenate them.

a = 1:20;
b = [2,5;12,16];

Range_1 = b(1,:); 
Range_2 = b(2,:);

bsxfun(@(Row_1,Row_2) [a(Row_1(1):Row_1(2)) a(Row_2(1):Row_2(2))], Range_1, Range_2)

Upvotes: 1

Related Questions