List of indexes for each row of a matrix without a for loop
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
George Aipal
le 24 Fév 2016
Commenté : George Aipal
le 24 Fév 2016
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 3
INDSETS = [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?
0 commentaires
Réponse acceptée
Stephen23
le 24 Fév 2016
Modifié(e) : Stephen23
le 24 Fév 2016
>> S = size(INDSETS);
>> reshape(DATA(:,INDSETS).',S(1),S(2),[])
or on one line:
>> reshape(DATA(:,INDSETS).',[size(INDSETS),size(DATA,1)])
both produce this output:
ans(:,:,1) =
9 1 3
8 3 2
2 9 8
2 1 9
ans(:,:,2) =
5 7 8
4 8 6
6 5 4
6 7 5
ans(:,:,3) =
5 7 9
1 9 3
3 5 1
3 7 5
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!