您可以按照示例here 使用元胞数组来定义索引。
具体来说,如果你有一个矩阵
x = ones(7,5,9);
你可以定义你想要的索引:
% 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, ':'};
然后从你的矩阵x 中获取这些索引就像
a = x(all_indexes{:});
b = x(indexes_2{:});
所以,你可以写一个类似的函数
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
它可以返回指定维度以外的所有单元格,并且在该方向上将返回window 给定范围内的单元格。所以在下面的代码中,a 和 b 是等价的。
a = extract_cells(x, 2, 1:5);
b = x(:, 1:5, :)