array indexing with another array in multidimensional matrices
Ältere Kommentare anzeigen
Thank you in advance for helping:
I have a multidimensional matrix (let's say 4D as example) and I want to index its values through another matrix which contains all possible combinations, as an example:
A=randi(10,5,4,3,2) %%is 4D matrix
and I want to index its "submatrices" through another vector, without performing for loops. In this specific case my indexing matrix would be:
idx=[1,1;2,1;3,1;1,2;2,2;3,2] %%is indexing matrix
through which I would like to obtain my resulting matrices:
A(:,:,1,1);
A(:,:,2,1);
A(:,:,3,1);
A(:,:,1,2);
A(:,:,2,2);
A(:,:,3,2);
by adding the last two indices with my indexing matrix:
A(:,:,B(1,:));
A(:,:,B(2,:));
A(:,:,B(3,:));
A(:,:,B(4,:));
A(:,:,B(5,:));
A(:,:,B(6,:));
but the two forms don't give the same results and I would like to code a form similar to the last one to obtain the first results, i.e. singe 2D matrices.
Thanks
Akzeptierte Antwort
Weitere Antworten (1)
Bruno Luong
am 2 Aug. 2020
Bearbeitet: Bruno Luong
am 2 Aug. 2020
A=randi(10,5,4,3,2)
idx=[1,1;2,1;3,1;1,2;2,2;3,2]
Then
sz=size(A);
Aidx = A(:,:,sub2ind(sz(3:4),idx(:,1),idx(:,2)))
6 Kommentare
gabriele fadanelli
am 2 Aug. 2020
Bruno Luong
am 2 Aug. 2020
Bearbeitet: Bruno Luong
am 2 Aug. 2020
What for-cycle? My code doesn't have any for-cycle.
If you want generic
sz = size(A);
p = size(idx,2);
c = repelem({':'},1,ndims(A)-p+1);
cidx = num2cell(idx,1);
c{end} = sub2ind(sz(end-p+1:end), cidx{:});
Aidx = A(c{:})
I hope you will know what to do with your variant multi-dimmensional array. It seems you just engage to something over the head.
gabriele fadanelli
am 2 Aug. 2020
gabriele fadanelli
am 2 Aug. 2020
Bruno Luong
am 2 Aug. 2020
I have impression you do something overly complicated.
You replace the indexing of last p-dimension by all combinations possible of the p last indexes.
This is insanely redundant, you already have your data with all the combination in the original form. Simple use permute/reshape will put them in the form you want no need those combination/indexing.
gabriele fadanelli
am 2 Aug. 2020
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!