0

Imagine a function where you want to output a snippet in a user-specified dimension of a n-dimensional matrix

function result=a(x,dim)
  window=1:10;
  dim=3;
  result=x(:,:,window);
end

How can I put window to the desired dimension? E.g. if dim=2; then result=x(:,window,:).

The way I can think of right now is to evaluate a string command that puts window in the correct position - or use a lot of if then else blocks. What's a better way of doing this?

user2305193
  • 2,079
  • 18
  • 39

1 Answers1

1

You can do this using a cell array to define your indexes, following the examples here.

Specifically, if you have a matrix

x = ones(7,5,9);

You can define the indexes you want like:

% get all the indexes in all dimensions
all_indexes = {':', ':', ':'};

% get all indexes in dimensions 1 and 3, and just indices 1:4 in dimension 2
indexes_2 = {':', 1:4, ':'}; 

And then get those indexes from your matrix x like

a = x(all_indexes{:});
b = x(indexes_2{:});

So, you could write a function like

function result=extract_cells(x, dim, window)
  % Create blank cell array {':', ':', ...} with entries ':' for each dimension
  % Edit (c/o Cris Luengo): need to use ndims(x) to get the number of dimensions
  num_dims = ndims(x)
  dims    = cell(1, num_dims);
  dims(:) = {':'};

  % Set the specified window of cells in the specified dimension
  dims{dim} = window;

  % Pick out the required cells
  result=x(dims{:});
end

Which could return all the cells in the dimensions other than one specified, and in that direction would return the cells in the range given by window. So in the following code, a and b would be equivalent.

a = extract_cells(x, 2, 1:5);
b = x(:, 1:5, :)