I have a 3-dimensional matrix C of size (m, n, k), and I have an index array ID of size (m,n) that indexes into the last dimension.
I tried indexing into it like this:
A = C(:,:,ID(:,:))
but that does not work. Is there a more compact way than the following function?
function B = matindex(C, ID)
B = zeros(size(ID));
for i = 1:size(C, 1)
for j = 1:size(C,2)
B(i,j) = C(i, j, ID(i,j));
end
end
end
Thanks!

 Akzeptierte Antwort

Thorsten
Thorsten am 16 Nov. 2015
Bearbeitet: Thorsten am 16 Nov. 2015

0 Stimmen

Use linear indexing
N = size(C,1)*size(C,2);
idx = [1:N]+(ID(1:N)-1)*N;
B = reshape(C(idx), size(C,1), size(C,2));

Weitere Antworten (0)

Kategorien

Gefragt:

am 16 Nov. 2015

Kommentiert:

KAE
am 11 Apr. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by