Fihop
Fihop

Reputation: 3177

access the element of multidimensional array given the subscript array

Given a multidimensional array A = MxMxMx...xM, where ndims(A)=n and the subscript array b=[a1, a2, ..., an]. How to get A(a1, a2, a3, ..., an)? I've tried A(b). It's not a correct way. And a correct way is to write a function to convert the subscript array to the index, saying i, and then we can use A(i) to get what I want. Is there an easier way?

Thanks

Upvotes: 1

Views: 42

Answers (1)

Marcin
Marcin

Reputation: 238467

I think that, the easiest way would be through linear indexing, using, e.g. sub2ind function.

BasCell = num2cell(b);    
i = sub2ind(size(A), BasCell{:});
A(i); % access ith element in A, using linear indexing

Upvotes: 1

Related Questions