Indexing one particular dimension regardless of number of dimensions

1 view (last 30 days)
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!

Accepted Answer

Guillaume
Guillaume on 23 Feb 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 Comments
Jacob Matthews
Jacob Matthews on 23 Feb 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 on 23 Feb 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.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!