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!
0 个评论
采纳的回答
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 个评论
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!