Extract sub array from d-dimensional array given indices for each dimension
13 views (last 30 days)
Show older comments
Michael Van de Graaff
on 20 May 2022
Edited: Michael Van de Graaff
on 21 May 2022
Suppose I have a d-dimensional array A which is size d_1 by d_2 by....by d_d and for each dimension i have a index vector vd_i such that vd_i(1)>=1 and vd_i(end)<= size(A, i). How do I extract the sub array A(vd_1,vd_2,...,vd_3) when d is arbitrary?
Edit: as mentioned by the wonderful Matt J, I meant that 1<= vd_i(j)<= size(A,i) for all i,j.
2 Comments
Matt J
on 20 May 2022
Edited: Matt J
on 21 May 2022
and for each dimension i have a index vector vd_i such that vd_i(1)>=1 and vd_i(end)<= size(A, i).
I think what you really mean is 1<= vd_i(j)<= size(A,i) for all i,j. If that's not what you meant then, well, you should check that it's true, because it's a requirement in any subscript indexing operation.
Accepted Answer
More Answers (2)
Voss
on 20 May 2022
% random 4-D (4x8x5x10) array A:
d_siz = [4 8 5 10];
A = randn(d_siz);
size(A)
% make the index vectors for each dimension
% into a cell array:
vd = {[2 3] [1 3 5 7] [2 3 4] 4:8};
% index into A in each dimension:
A_subs = A(vd{:});
size(A_subs)
2 Comments
dpb
on 20 May 2022
Did you try the obvious???
Smallish example, but works in general...
>> d=3;A=reshape(1:4^d,4,4,[]) % make up a sample array to play with that can read
>> A
A(:,:,1) =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
A(:,:,2) =
17 21 25 29
18 22 26 30
19 23 27 31
20 24 28 32
A(:,:,3) =
33 37 41 45
34 38 42 46
35 39 43 47
36 40 44 48
A(:,:,4) =
49 53 57 61
50 54 58 62
51 55 59 63
52 56 60 64
>>
>> v1=2:3;v2=v1;v3=v1; % pick middle two of each dimension
>> A(v1,v2,v3)
ans(:,:,1) =
22 26
23 27
ans(:,:,2) =
38 42
39 43
>>
is, by inspection, the array elements of 2nd, 3rd plane and the central four elements of each, respectively.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!