how to extract elements along specified dimension of array

when e.g. selecting all elements in the 2nd dimension and the first element of all remaining dimensions of an array, for a 3-dimensional array one would write: A(1,:,1)
how to program this elegantly when the dimension over which I want the elements (2 in the example) is a variable itself, whose value is unknown until runtime ?
thanks!!

 採用された回答

Jonathan Sullivan
Jonathan Sullivan 2012 年 3 月 16 日

1 投票

A = rand(100,100,10,10);
dim = 4;
sz = size(A);
inds = repmat({1},1,ndims(A));
inds{dim} = 1:sz(dim);
A(inds{:})

1 件のコメント

Peter
Peter 2012 年 3 月 16 日
thanks a lot. exactly what i needed.
just for my understanding: inds is a cell array. what exactly does inds{:} give? looks like seperate doubles.
thanks again!

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

その他の回答 (2 件)

per isakson
per isakson 2012 年 3 月 15 日

0 投票

A(ixi,ixj,ixk)
where ixi,ixj,and ixk are numerical vectors (/scalar) of integers. ":" would correspond to (1:number_of_element_in_dimension). Or with logical indexing
A(isi,isj,isk)
where isi,isj,isk are logical vectors all with the length "number_of_element_in_dimension". ":" would be true(1,number_of_element_in_dimension).
The elegance will be in the calculation of ixi,ixj,and ixk or isi,isj,isk.
Walter Roberson
Walter Roberson 2012 年 3 月 15 日

0 投票

Something like this,
DIM = 2; %changed at runtime
idxexpr = { repmat({1}, 1, DIM - 1), {':'}, repmat({1}, 1, ndim(A)-DIM) };
A(idxexpr{:})

3 件のコメント

Peter
Peter 2012 年 3 月 15 日
hi Walter, thanks! but idxexpr becomes a cell array of cells, resulting in the error:
"Function 'subsindex' is not defined for values of class 'cell'"
ran across this myself which made me decide to construct a characterstring similar to your idxexpr and than use 'eval'.
thought however that something more elegant than eval should be possible here.
Walter Roberson
Walter Roberson 2012 年 3 月 15 日
I have done it successfully before, my post is either on the newsgroup or somewhere in Answers. _Finding_ the post would take longer than reinventing it!
Try
idxexpr = [num2mat(ones(1,DIM-1)), {':'}, num2mat(ones(1,ndim(A)-DIM))];
Peter
Peter 2012 年 3 月 16 日
num2mat doesn't seem to exist. can you maybe comment on what class idxexpr should be to make it work as a subscript expression? that would give some direction to my own attempts. it seems like a cell array doesn't work. ('ndim' should be 'ndims' btw.)
thanks again!

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

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by