Colon Access Matrix programmatically

I have a matrix awith an unknown number of dimensions.

I want to access it, like a(:,:,:,:,:, ... ,:,1). In other words, setting only the last measurement.

How to do this without doing a lot of math and treating it as a 1-dimensional array . I know this solution works, but it’s a mess and it’s very difficult to implement when each dimension has a different size (and you don’t even know the number of dimensions)

+4
source share
3 answers
% get number of dimensions of a
d = ndims(a)

% create cell array with indexes for each dimension
indexes = repmat({':'}, 1, d-1)
indexes{end+1} = 1

% access matrix
a(indexes{:})
+4
source

I have a different opinion than yours. You said:

, , , ( , )

. .

MATLAB , MATLAB n-D , :

  • .
  • , , .. , .
  • , . ( ).

, :

a=randi(12,2,2,2,2)

a(:,:,1,1) =

 7     8
10     5


a(:,:,2,1) =

 4     6
 6     5


a(:,:,1,2) =

 7     6
 9     6


a(:,:,2,2) =

 2     4
 1     4

a.

b=a(:)

b =

 7
10
 8
 5
 4
 6
 6
 5
 7
 9
 6
 6
 2
 1
 4
 4

, , . , 1 ( , ).

dimToAccess=1;
sz=size(a);
c=b(prod(sz(1:end-1))*(dimToAccess-1)+1:prod(sz(1:end-1))*(dimToAccess));

.

a=randi(12,2,2,2,2)

a(:,:,1,1) =

 7     8
10     5


a(:,:,2,1) =

 4     6
 6     5


a(:,:,1,2) =

 7     6
 9     6


a(:,:,2,2) =

 2     4
 1     4

b=a(:);
dimToAccess=1;
sz=size(a);
c=b(prod(sz(1:end-1))*(dimToAccess-1)+1:prod(sz(1:end-1))*(dimToAccess));

%Test - It should produce 1 as output.
isequal(reshape(c,[size(a,1) size(a,2) size(a,3)]),a(:,:,:,dimToAccess))

, 4 .

0

Just resize, moving the last to the first.

x = shiftdim(x,ndims(x)-1)

Then you can simply work with the first elements. Since Matlab organizes the main data column, you do not need to worry about all the ends :. Just index the first column by indexing the first elements.

x(1:size(x,1)) = whatever

and come back at the end, if you want, with shiftdim.

0
source

All Articles