Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
Jabor Avatar asked Jul 19 '17 18:07

Jabor


People also ask

How do you access elements in a multidimensional array?

An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. int x = a[1,1]; Console.

How do you access elements of an array in MATLAB?

To access elements in a range of rows or columns, use the colon . For example, access the elements in the first through third row and the second through fourth column of A . An alternative way to compute r is to use the keyword end to specify the second column through the last column.

Can MATLAB handle multidimensional arrays?

You can use MATLAB functions such as randn , ones , and zeros to generate multidimensional arrays in the same way you use them for two-dimensional arrays.

How do you call an element in a matrix in MATLAB?

For example, to access a single element of a matrix, specify the row number followed by the column number of the element. e is the element in the 3,2 position (third row, second column) of A . You can also reference multiple elements at a time by specifying their indices in a vector.


1 Answers

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{:});
like image 156
EBH Avatar answered Nov 15 '22 00:11

EBH