Extract sub array from d-dimensional array given indices for each dimension

12 次查看(过去 30 天)
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 个评论
Matt J
Matt J 2022-5-20
编辑:Matt J 2022-5-21
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.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2022-5-20
编辑:Matt J 2022-5-20
If you have your vd_i in a cell array V={vd_1,vd_2,...,vd_d}, you can do
A(V{:})

更多回答(2 个)

Voss
Voss 2022-5-20
% random 4-D (4x8x5x10) array A:
d_siz = [4 8 5 10];
A = randn(d_siz);
size(A)
ans = 1×4
4 8 5 10
% 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)
ans = 1×4
2 4 3 5

dpb
dpb 2022-5-20
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by