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