Jabor
Jabor

Reputation: 105

Matlab - Accessing a part of a multidimensional array

I'm trying to access a part of a multidimensional array in Matlab - it could be done like this: X(2:3, 1:20, 5, 4:7) However, neither the number of elements, nor the ranges are fixed, so I want to provide the indices from arrays - for the above example they'd be

ind1 = [2 1 5 4];
ind2 = [3 20 5 7];

For a fixed number of dimensions this is not a problem (X(ind1(1):ind2(1),...), but since they are not I'm not sure how to implement this in Matlab. Is there a way? Or should I approach this differently?

Upvotes: 6

Views: 245

Answers (2)

EBH
EBH

Reputation: 10450

Using comma separated lists you can make it a more quick and friendly:

% some test data
ind1 = [2 1 5 4];
ind2 = [3 20 5 7];
X = randi(99,20,20,20,20);

% get all subscripts in column format
vecs = arrayfun(@colon,ind1,ind2,'un',0);
% extract the values
result = X(vecs{:});

Upvotes: 6

Leander Moesinger
Leander Moesinger

Reputation: 2462

There probably is a more elegant way, but this is a difficult problem so here is one solution:

% some test data
ind1 = [2 1 5 4];
ind2 = [3 20 5 7];
X = randi(99,20,20,20,20);

% get all subscripts in column format
vecs = arrayfun(@colon,ind1,ind2,'Uniformoutput',false);
subs = combvec(vecs{:}).';
% manual sub2ind for a matrix where each row contains one subscript
sizeX = size(X);
idx = cumprod([1 sizeX(1:end-1)])*(subs - [zeros(size(subs,1),1) ones(size(subs,1),size(subs,2)-1)]).';
% reshape
result = reshape(X(idx),ind2-ind1+1);

Subscripts to indices conversion based on Gnovices answer in Indexing of unknown dimensional matrix

Upvotes: 4

Related Questions