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

조회 수: 27 (최근 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에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by