Given a 3D array:
a = rand(10, 10, 10);
and an integer index array:
idx = ceil(10 * rand(3, 1000));
is there a way (a clever indexing trick?) to vectorize the following loop:
b = zeros(1, 1000);
for i = 1:1000
b(i) = a(idx(1, i), idx(2, i), idx(3, i));
end
Thanks!

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 10 月 29 日
編集済み: Azzi Abdelmalek 2013 年 10 月 29 日

1 投票

ii=sub2ind(size(a),idx(:,1),idx(:,2),idx(:,3));
b =a(ii)

1 件のコメント

Frank
Frank 2013 年 10 月 30 日
Brilliant! This is exactly what I was looking for. Minor issue: answer uses transpose of idx compared to OP's definition (have to prepend: idx = idx'). Thank you.

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

その他の回答 (1 件)

Matt J
Matt J 2013 年 10 月 29 日

1 投票

idxcell=num2cell(idx,2);
lidx=sub2ind(size(a), idxcell{:});
b=a(lidx);

1 件のコメント

Frank
Frank 2013 年 10 月 30 日
Thank you Matt! sub2ind works like a charm. That's what I had in mind with "clever indexing".

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

カテゴリ

ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索

質問済み:

2013 年 10 月 29 日

コメント済み:

2013 年 10 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by