Extract sub array from d-dimensional array given indices for each dimension
36 ビュー (過去 30 日間)
表示 古いコメント
Michael Van de Graaff
2022 年 5 月 20 日
編集済み: Michael Van de Graaff
2022 年 5 月 21 日
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 件)
Voss
2022 年 5 月 20 日
% 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)
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.
0 件のコメント
参考
カテゴリ
Find more on Resizing and Reshaping Matrices 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!