Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab last dimension access on ndimensions matrix

I have as entry a matrix which can have an several number of dimensions : n × m or n × m × p or n × m × p × q or ...

What I want to do is to access to the last dimension, something like:

data = input(:,:,1)

The problem is that the number of : can change.

like image 952
Romain Avatar asked Nov 13 '13 13:11

Romain


People also ask

How do you access multidimensional arrays in MATLAB?

To access elements in a multidimensional array, use integer subscripts just as you would for vectors and matrices. For example, find the 1,2,2 element of A , which is in the first row, second column, and second page of A .

How do you check dimensions in MATLAB?

N = ndims( A ) returns the number of dimensions in the array A . The number of dimensions is always greater than or equal to 2. The function ignores trailing singleton dimensions, for which size(A,dim) = 1 .

What is the MATLAB command to get the dimension of the matrix A?

Description. sz = size( A ) returns a row vector whose elements are the lengths of the corresponding dimensions of A . For example, if A is a 3-by-4 matrix, then size(A) returns the vector [3 4] .

What is end index in MATLAB?

The end class method returns the index value for the last element of the first dimension (from which 1 is subtracted in this case). The original expression is evaluated as: A(3-1,:) For an example of an overload of end in a class that customizes indexing, see Customize Parentheses Indexing for Mapping Class.


2 Answers

You should make use of the fact that indices into an array can be strings containing ':':

>> data = rand(2, 2, 2, 5);
>> otherdims = repmat({':'},1,ndims(data)-1);
>> data(otherdims{:}, 1)
ans(:,:,1) =
    7.819319665880019e-001    2.940663337586285e-001
    1.006063223624215e-001    2.373730197055792e-001
ans(:,:,2) =
    5.308722570279284e-001    4.053154198805913e-001
    9.149873133941222e-002    1.048462471157565e-001

See the documentation on subsref for details.

like image 50
Rody Oldenhuis Avatar answered Oct 16 '22 04:10

Rody Oldenhuis


It is a bit of a hack, but here is how you can do it:

data = rand(2,2,3);

eval(['data(' repmat(':,',1,ndims(data)-1) '1)'])

This will give (depending on the randon numbers):

ans =

      0.19255      0.56236
      0.62524      0.90487
like image 38
Dennis Jaheruddin Avatar answered Oct 16 '22 02:10

Dennis Jaheruddin