代码之家  ›  专栏  ›  技术社区  ›  rlbond

变维上的matlab子矩阵

  •  1
  • rlbond  · 技术社区  · 14 年前

    我有一个变维矩阵,x。我想要一个函数,它可以得到x在一维中的前半部分。也就是说,我想要这样的东西:

    function x = variableSubmatrix(x, d)
        if d == 1
            switch ndims(x)
                case 1
                    x = x(1:end/2);
                case 2
                    x = x(1:end/2, :);
                case 3
                    x = x(1:end/2, :, :);
                (...)
            end
        elseif d == 2
            switch ndims(x)
                case 2
                    x = x(:, 1:end/2);
                case 3
                    x = x(:, 1:end/2, :);
                (...)
            end
        elseif (...)
        end
    end
    

    我不太确定该怎么做。我需要它的速度快,因为这将在计算中使用很多次。

    3 回复  |  直到 14 年前
        1
  •  7
  •   gnovice    14 年前

    这应该可以做到:

    function x = variableSubmatrix(x, d)
      index = repmat({':'},1,ndims(x));  %# Create a 1-by-ndims(x) cell array
                                         %#   containing ':' in each cell
      index{d} = 1:size(x,d)/2;          %# Create an index for dimension d
      x = x(index{:});                   %# Index with a comma separated list
    end
    

    上面先创建一个1-by- ndims(x) 单元阵列 ':' 在每个单元格中。与维度相对应的单元格 d 然后用一个包含数字1到尺寸一半的向量替换 D . 然后,单元格数组的内容输出为 comma-separated list (使用 {:} 语法)并用作 x . 这是因为 “:” : 在索引语句中使用时,处理方式相同(即“此维度的所有元素”)。

        2
  •  0
  •   eykanal    14 年前

    你可以使用 s = size(X) 获取的尺寸 X 然后尝试 X(1:floor(s(1)),:) 得到矩阵的一半。

    注意 size 返回包含每个维度中的长度的向量数组(例如,2x3矩阵将返回 [2 3] )因此,你可能想改变 s(1) 到你需要的尺寸。

    例子:

    a = [1 2 3 4; 5 6 7 8;]
    
    s = size(a);          % s = [2 4]
    
    b = a(1:s(1)/2,:);    % b = [1 2 3 4];
    c = a(:,1:s(2)/2);    % c = [1 2; 5 6];
    
        3
  •  0
  •   Olivier Verdier    14 年前

    值得一提的是,这里是Python中的解决方案(使用 numpy ):

    将尺寸减半 i :

    def halve(x,i):
        return x[(slice(None),)*i+(slice(x.shape[i]/2),)]
    
    x = zeros([2,4,6,8])
    y = halve(x,2) # dimension 2 was 6
    y.shape # (2,4,3,8) # dimension 2 is now 3
    

    如果你只想把第一个维度减半,那么 x[:len(x)/2] 就足够了。

    编辑

    我对我以前的解决方案有一些怀疑的意见, x[LeN(x)/2 ] ,下面是一个例子:

    x=zeros([4,2,5,6,2,3]) # first dimension is 4
    len(x) # 4
    x.shape # 4,2,5,6,2,3
    x[:len(x)/2].shape # 2,2,5,6,2,3 <- first dimension divided by two