Matrix DATA contains some data, and matrix INDSETS contains the indexes to be extracted from each row of DATA.
Example:
DATA = [8 9 3 1 2; 4 5 8 7 6; 1 5 9 7 3]DATA = 8 9 3 1 2 4 5 8 7 6 1 5 9 7 3INDSETS = [2 4 3; 1 3 5; 5 2 1; 5 4 2]INDSETS = 2 4 3 1 3 5 5 2 1 5 4 2
For EACH row of DATA, I would like to extract its N subsets as given by each row of INDSETS (where N = number of rows in INDSETS). For instance, for the first row of DATA, its subsets are:
DATA(1, :)(INDSETS)ans = 9 1 3 8 3 2 2 9 8 2 1 9
For the 2nd row of DATA, its subsets are:
DATA(2, :)(INDSETS)ans = 5 7 8 4 8 6 6 5 4 6 7 5
and so on. A possible slow solution would be to preallocate a 3D array C to store the results, and run a for loop row by row, saving the results of each iteration on the 3rd dimension of C:
Slow solution:
C = zeros(size(INDSETS, 1), size(INDSETS, 2), size(DATA, 1));for i = 1:size(DATA, 1) C(:, :, i) = DATA(i, :)(INDSETS); end
Is there a more efficient way to do this without a for loop, perhaps a vectorized solution?
Best Answer