フィルターのクリア

Indexing arrays of varying dimensionality.

2 ビュー (過去 30 日間)
Lionel Pöffel
Lionel Pöffel 2021 年 3 月 2 日
編集済み: Stephen23 2022 年 2 月 23 日
I have to handle arrays of varying dimensionality in one loop, and I have to index individual elements of those arrays.
From what I have seen in the general help, the only solution seems to be to do a stupid and unflexible switch-case-like approach, such as
sz=size(arr);
switch length(sz)
case 1:
ind1=calc_ind(1);
elem_val=arr(ind1);
case 2:
ind1=calc_ind(1);
ind2=calc_ind(2);
elem_val=arr(ind1,ind2);
case 3:
ind1=calc_ind(1);
ind1=calc_ind(2);
ind3=calc_ind(3);
elem_val=arr(ind1,ind2,ind3);
end
This makes it impossible to handle arrays of arbitrary dimensionality and is also very stupid and repetitive.
Using linear indices doesn't seem to help, because also sub2ind() needs different calls for each dimensionality.
Is there not an easier solution. like
sz=size(arr);
for d=1:length(sz)
ind_arr(d)=calc_index(d);
end
LinIndex=sub2ind(sz,ind_arr);
elem_val=arr(LinIndex);

採用された回答

Stephen23
Stephen23 2021 年 3 月 2 日
編集済み: Stephen23 2022 年 2 月 23 日
  1 件のコメント
Stephen23
Stephen23 2021 年 3 月 2 日
Complete working example:
arr = rand(7,6,5,4,3,2);
idx = [5,3,4,4,1,1];
tmp = num2cell(idx);
x = arr(tmp{:})
x = 0.2769
y = arr(5,3,4,4,1,1)
y = 0.2769

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

その他の回答 (1 件)

Lionel Pöffel
Lionel Pöffel 2021 年 3 月 3 日
Thanks, that works beautifully!

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by