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 ビュー (過去 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
Sudharsan Srinivasan 2017 年 6 月 22 日
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 :-)
dpb
dpb 2017 年 6 月 22 日
So 'Accept' an answer to indicate thread subject closed if nothing else...

サインインしてコメントする。

その他の回答 (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' ... :)
Image Analyst
Image Analyst 2017 年 6 月 22 日
I've wondered the same thing. I agree with you.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by