Using cell array for indexing

2 ビュー (過去 30 日間)
Lionel Pöffel
Lionel Pöffel 2021 年 8 月 2 日
コメント済み: Lionel Pöffel 2021 年 8 月 2 日
I have matrices of varying dimensionality I need to index.
So just writing A(i1,...,in) is not an option because n can vary in my application.
What is known to work for getting a single element out of A is using a cell array:
IndArray={i1,...,in}
Elem=A(IndArray{:})
However I'd like to do something like SubMatrix= A(i1,i2,...,im,:,:,...,:), where m<n. Is there a way to do that?
The following does not work:
IndArray={i1,...,im}
SubMatrix=A(IndArray{:})
Thanks in advance for any hints.

採用された回答

Rik
Rik 2021 年 8 月 2 日
I would suggest something like this:
IndArray={i1,...,im}
for dim=(numel(IndArray)+1):ndims(A)
IndArray{dim}=1:size(A,dim);
end
SubMatrix=A(IndArray{:})

その他の回答 (2 件)

Stephen23
Stephen23 2021 年 8 月 2 日
編集済み: Stephen23 2021 年 8 月 2 日
No need for a loop, here is the simple and efficient MATLAB approach:
IndArray = {i1,..,im};
IndArray(1+end:ndims(A)) = {':'};
SubMatrix = A(IndArray{:})
How it works: MATLAB always allows a scalar element on the RHS to be allocated to any number of elements on the LHS. This applies to any array class: numeric, cell (as above), char, string, struct, etc.
  1 件のコメント
Lionel Pöffel
Lionel Pöffel 2021 年 8 月 2 日
Hello Stephen,
thanks for your answer. That is, of course, an additional improvement.

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


Lionel Pöffel
Lionel Pöffel 2021 年 8 月 2 日
Hi Rik, that seems to work, thanks.
DGM posted an answer that surprisingly also seems to work but unfortunately deleted it (thanks to him/her as well).
For completeness I will note it here:
IndArray={i1,...,im}
for dim=(numel(IndArray)+1):ndims(A)
IndArray(dim)={':'};
end
SubMatrix=A(IndArray{:})
  1 件のコメント
DGM
DGM 2021 年 8 月 2 日
Sorry about that. I tried reading your other posts to try to figure out what exactly you were trying to do and had the feeling that I had misunderstood the intent.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by