Effacer les filtres
Effacer les filtres

I want to index across multiple dimensions using a vector, as opposed to comma notation

2 vues (au cours des 30 derniers jours)
SeanC
SeanC le 29 Mar 2017
Modifié(e) : Stephen23 le 29 Mar 2017
E.g.
I have a matrix A. This matrix will have a different number of dimensions depending upon what is input to my function.
I want to be able to use a vector(i.e. IndexingVector = [2 3 4 5]) to get the information I need:
A(IndexingVector) would be the same as saying A(2,3,4,5).
This means that if A happens to have a different number of dimensions when the function has different inputs, I could still use IndexingVector to get the information I need.
Thanks

Réponses (1)

Stephen23
Stephen23 le 29 Mar 2017
Modifié(e) : Stephen23 le 29 Mar 2017
Lets first create some fake data:
>> A = randi(9,4,3,2); % the data
>> V = [3,2,1]; % the indices in a vector
>> C = num2cell(V);
>> A(3,2,1) % writing it out
ans =
7
Method One: a simple comma-separated list:
>> A(C{:})
ans =
7
Method Two: use sub2ind:
>> A(sub2ind(size(A),C{:}))
ans =
7
Method Three: call subsref directly:
>> subsref(A,struct('type','()','subs',{num2cell(V)}))
ans =
7

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by