Borrar filtros
Borrar filtros

Indexing one particular dimension regardless of number of dimensions

1 visualización (últimos 30 días)
I have a structure of several dimension (7 right now) that I will be adding dimensions to in the future. In a section of my code I need to isolate the third dimension into it's three components which right now I do like
outX = in(:,:,1,:,:,:,:); outY = in(:,:,2,:,:,:,:); outZ = in(:,:,3,:,:,:,:);
Is there a way to generalize this without having to edit the number of colons in the statement?
ex:
outX = coolFunction(in,3,1); outY = coolFunction(in,3,2); outZ = coolFunction(in,3,3);
Thanks!

Respuesta aceptada

Guillaume
Guillaume el 23 de Feb. de 2015
function out = coolFunction(in, dim, page)
validateattributes(dim, {'numeric'}, {'scalar', 'positive', '<=', ndims(in)});
validateattributes(page, {'numeric'}, {'scalar', 'positive', '<=', size(in, dim)});
alldims = arrayfun(@(d) 1:d, size(in), 'UniformOutput', false);
alldims{dim} = page;
out = in(alldims{:});
end
  2 comentarios
Jacob Matthews
Jacob Matthews el 23 de Feb. de 2015
Super cool answer... and I won't pretend to understand it initially, but I'll study it.
I'm mostly glad I wasn't overlooking some existing function or indexing notation.
Thanks!
Guillaume
Guillaume el 23 de Feb. de 2015
Basically, it creates a cell array (with arrayfun) where each cell is an array from 1 to the size of each dimension (what colon would do), then replace the cell of the required dimension with just the page number you want in that dimension.
The last line uses expansion of cell array into comma separated list to index the matrix.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by