matlab:指定要索引的维度

matlab:指定要索引的维度,matlab,Matlab,假设有一个函数,您希望在其中以用户指定的n维矩阵维度输出代码段 function result=a(x,dim) window=1:10; dim=3; result=x(:,:,window); end 如何将窗口设置为所需的尺寸?例如,如果尺寸=2;然后结果=x:,窗口: 我现在想到的方法是计算一个字符串命令,该命令将窗口置于正确的位置,或者使用大量if-then-else块。执行此操作的更好方法是什么?您可以使用单元格数组来定义索引,如下示例所示 具体来说,如果你有一个矩阵

假设有一个函数,您希望在其中以用户指定的n维矩阵维度输出代码段

function result=a(x,dim)
  window=1:10;
  dim=3;
  result=x(:,:,window);
end
如何将窗口设置为所需的尺寸?例如,如果尺寸=2;然后结果=x:,窗口:


我现在想到的方法是计算一个字符串命令,该命令将窗口置于正确的位置,或者使用大量if-then-else块。执行此操作的更好方法是什么?

您可以使用单元格数组来定义索引,如下示例所示

具体来说,如果你有一个矩阵

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中得到这些索引,就像

你可以写一个函数,比如

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
它可以返回除一个指定维度以外维度中的所有单元格,并在该方向返回窗口给定范围内的单元格。所以在下面的代码中,a和b是等价的

a = extract_cells(x, 2, 1:5);
b = x(:, 1:5, :)

@谢谢,我更新了我原来的帖子。
a = extract_cells(x, 2, 1:5);
b = x(:, 1:5, :)