function-style array indexing

1 回表示 (過去 30 日間)
Ben Mitch
Ben Mitch 2013 年 3 月 13 日
編集済み: per isakson 2016 年 8 月 5 日
Hi
This problem keeps coming up for me over the years, and there must be a standard solution, so perhaps someone knows it, I can't ever google it up.
Say I have an array A of any number of dimensions, and I want to apply an indexing operation to the last dimension. Now, if it's 2D, I just use:
B = A(:, ii);
If it's 3D, I use:
B = A(:, :, ii);
but what if it's n-D? Afaik there is no syntax in the language for this, so I'd have to use some function. A function "index_into()", for instance, to give:
B = index_into(A, n, ii);
At the moment, I always end up doing some horrible mash like:
X = permute(A, [ndims(A) ...]);
X = X(ii, :);
X = reshape(X, ...);
B = permute(X, ...);
Surely there must be a better way...? Any suggestions?
Cheers

採用された回答

Walter Roberson
Walter Roberson 2013 年 3 月 13 日
idxcell = repmat({':'}, 1, ndims(A));
idxcell{n} = ii;
A(idxcell{:})
  2 件のコメント
Daniel Shub
Daniel Shub 2013 年 3 月 13 日
This is the exact recommendation in Loren's blog.
Ben Mitch
Ben Mitch 2013 年 3 月 13 日
Nice, thanks. I think I had seen that index-by-comma-separated-list before, but it hadn't taken root in my mind. Wonder, though, if a syntax would be possible that made this a bit more intuitive. Just curious...
A(..., ii)?

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by