Quickest way to get points in a matrix given two 1-D arrays?

1 回表示 (過去 30 日間)
James
James 2012 年 2 月 27 日
Let's say that A is an NxN matrix, and B and C are 1-D arrays of the same size, containing numbers between 1 and N.
Is there a better way than going through a "for loopvar=1:length(B)" loop to get the values of A that correspond to the (Bi, Ci)
Example: A is a 5x5 matrix B contains [1 3 5 2 4 5] C contains [2 1 4 3 5 2]
What would be the quickest way to get:
  • A(1,2) (Corrseponding to A(B(1), C(1)))
  • A(3,1) (Corrseponding to A(B(2), C(2)))
  • A(5,4)
  • A(2,3)
  • A(4,5)
  • A(5,2) (Corrseponding to A(B(6), C(6)))
I'd like the quickest way to get this, since I need to run this calculation an enormous number of times with matrices much larger than a 5x5.

採用された回答

Honglei Chen
Honglei Chen 2012 年 2 月 27 日
A(sub2ind(size(A),B(:),C(:)))
  1 件のコメント
James
James 2012 年 2 月 28 日
Exactly what I was looking for. Thanks!

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

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2012 年 2 月 27 日
Apart = diag(A(B(:),C(:)))
  3 件のコメント
Sean de Wolski
Sean de Wolski 2012 年 2 月 27 日
True, but for small index vectors it's faster, i.e. 5 elements
. I tested it the usual way for my reply in this question:
http://www.mathworks.com/matlabcentral/answers/11082-how-do-i-index-into-a-2d-matrix-using-two-equal-length-r-and-c-vectors
James
James 2012 年 2 月 28 日
I like this for smaller sets, but I'm running a Monte carlo simulation with several thousand data points. The other answer is quicker for the larger data sets I'm using. Still, this is a good trick for smaller sets. It never hurts to have multiple ways of solving things.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by