How will I collect/pick only certain values from a matrix, whose co-ordinates (which row and column to be picked) is specified in another vector?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sudharsan Srinivasan
le 21 Juin 2017
Commenté : Image Analyst
le 22 Juin 2017
I have two vectors say "a" and "b" of size 1by35 which stores certain values that specify the row and column number. I have another matrix say "c" of size 200by50 which has some values throughout. Now I want to pick/collect only the numbers form the matrix "c" that is specified in the vector "a" and "b". For example, let's say a = [10 56 47 30 25 67 ..... 98] and b = [49 32 21 46 17 27 ..... 23]. The elements in the vector "a" denotes the row and "b" denotes the column. Now I want to pick the element from the matrix "c" (which is a 200by50 array) that corresponds to 10th row and 49th column, 56th row and 32nd column etc..up to 98th row and 23rd column. I have to eventually get again a 1by35 vector that has the collected elements from the matrix "c". How can I code this ?
0 commentaires
Réponse acceptée
dpb
le 21 Juin 2017
Modifié(e) : Image Analyst
le 21 Juin 2017
res=c(sub2ind(size(c),a,b));
2 commentaires
Plus de réponses (1)
Image Analyst
le 21 Juin 2017
dpb gave a very MATLABy solution, and it's a nice, clever, compact one. By chance if you want the brute force, easy-to-understand one, it's:
for k = 1 : length(a)
output(k) = c(a(k), b(k));
end
They both seem to take about the same amount of time. Sometimes one is faster, other times the other is faster. Anyway, for tiny data like this, either takes just a few microseconds.
2 commentaires
dpb
le 21 Juin 2017
I've always wondered why there wasn't a syntax to imply that simply
res=c(a,b);
where a, b are vectors as OP's case can't mean to simply take the two vectors in pairs. Instead, Matlab expands to include all possible pairs of a,b.
I suppose it would just add more overhead that having once chosen a particular implementation any other would require other nonregular syntax. But, in my experience it's been the former I've wanted far more often than the latter when had such indexing vectors...just sayin' ... :)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!