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 views (last 30 days)
Show older comments
Sudharsan Srinivasan
on 21 Jun 2017
Commented: Image Analyst
on 22 Jun 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 Comments
Accepted Answer
More Answers (1)
Image Analyst
on 21 Jun 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 Comments
dpb
on 21 Jun 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' ... :)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!