MATLAB: Use a matrix as an index to take elements from a vector and create a new matrix

matrix index

How can I take elements of matrix A and use it like indices of the vector B for obtaining a new matrix C that contain elements B between indices?
For example, I have A and B and I want C
A = [2, 5; 6, 9; 10, 14]
B = [ 3, 4, 6 , 10, 9, 5, 34, 33, 90, 31, 2, 9, 14, 16]
C = [4, 6, 10, 9 ; 5, 34, 33, 90; 31, 2, 9, 14, 16]

Best Answer

In MATLAB, rows of matrix must have same length. You need to use a cell array
A = [2, 5; 6, 9; 10, 14];
B = [3, 4, 6, 10, 9, 5, 34, 33, 90, 31, 2, 9, 14, 16];
C = cell(1, size(A, 1));
for i = 1:size(A, 1)
C{i} = B(A(i,1):A(i,2));
end
Result
>> C{1}
ans =
4 6 10 9
>> C{2}
ans =
5 34 33 90
>> C{3}
ans =
31 2 9 14 16