Indexing one particular dimension regardless of number of dimensions

조회 수: 4 (최근 30일)
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!

채택된 답변

Guillaume
Guillaume 2015년 2월 23일
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
Jacob Matthews
Jacob Matthews 2015년 2월 23일
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 2015년 2월 23일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by