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?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sudharsan Srinivasan
el 21 de Jun. de 2017
Comentada: Image Analyst
el 22 de Jun. de 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 comentarios
Respuesta aceptada
dpb
el 21 de Jun. de 2017
Editada: Image Analyst
el 21 de Jun. de 2017
res=c(sub2ind(size(c),a,b));
2 comentarios
dpb
el 22 de Jun. de 2017
So 'Accept' an answer to indicate thread subject closed if nothing else...
Más respuestas (1)
Image Analyst
el 21 de Jun. de 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 comentarios
dpb
el 21 de Jun. de 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' ... :)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!