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 次查看(过去 30 天)
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 ?

采纳的回答

dpb
dpb 2017-6-21
编辑:Image Analyst 2017-6-21
res=c(sub2ind(size(c),a,b));
  2 个评论
Sudharsan Srinivasan
Hello Sir,
Thank you very much for your answer. I had been trying res = c(a,b) and ended up with the same problem you have mentioned. But 'sub2ind' command works very well and quicker than a for loop. Once again thanks a million for your time :-)

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2017-6-21
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 个评论
dpb
dpb 2017-6-21
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' ... :)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by