Accessing an array element whose subscript is stored in a vector

Hello Everybody,
Given an array e.g. A=[[1,2,3];[4,5,6];[7,8,9]]
I would like to access an element in the array, whose index is stored in a vector e.g. ind=[2,2]
A(ind(1),ind(2)) should return 5 and works fine, but only as long as the array is 2-dimensional. I would like to make this work for arbitrary dimensions (the vector would have the according dimension).
Thanks in advance,
Christian

 採用された回答

Oleg Komarov
Oleg Komarov 2011 年 4 月 15 日

0 投票

A = [1,2,3
4,5,6
7,8,9];
% Add third dimension
A(:,:,2) = A+9;
% Index
ind = [2,3,2];
ind = num2cell(ind);
A(sub2ind(size(A),ind{:}))

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by