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?
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.
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.
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.
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.
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{:});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With