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

26 ビュー (過去 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.
Michael Van de Graaff
Michael Van de Graaff 2022 年 5 月 21 日
yes, that's true my bad

サインインしてコメントする。

採用された回答

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
  2 件のコメント
Michael Van de Graaff
Michael Van de Graaff 2022 年 5 月 21 日
thank you! the A(vd{:}) was what i needed.
Voss
Voss 2022 年 5 月 21 日
You're welcome!

サインインしてコメントする。


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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by