【问题标题】:matlab: specify which dimension to index [duplicate]matlab:指定要索引的维度[重复]
【发布时间】:2019-06-30 23:58:45
【问题描述】:

想象一个函数,您希望在 n 维矩阵的用户指定维度中输出一个 sn-p

function result=a(x,dim)
  window=1:10;
  dim=3;
  result=x(:,:,window);
end

如何将window 放入所需的维度?例如。如果dim=2; 然后result=x(:,window,:)

我现在能想到的方法是评估一个将 window 放在正确位置的字符串命令 - 或使用大量 if then else 块。有什么更好的方法?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以按照示例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 给定范围内的单元格。所以在下面的代码中,ab 是等价的。

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

    【讨论】:

    • @CrisLuengo 谢谢,更新了我原来的帖子。
    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多