首页 文章

从矩阵的每一行中删除一个元素,每个元素位于不同的列中

提问于
浏览
2

如何在for循环中一次删除一行时,如何删除矩阵中不是全部为直线的元素?

例:

[1 7 3 4;
 1 4 4 6;
 2 7 8 9]

给定一个向量(例如[2,4,3])如何删除每一行中的元素(向量中的每个数字对应于列号),而不是一次遍历每一行并删除每个元素?

示例输出将是:

[1 3 4;
 1 4 4;
 2 7 9]

2 回答

  • 1

    这是一种使用bsxfunpermute来解决3D数组情况的方法,假设您要在所有3D切片中每行删除索引元素 -

    %// Inputs
    A = randi(9,3,4,3)
    idx = [2 4 3]
    
    %// Get size of input array, A
    [M,N,P] = size(A)
    
    %// Permute A to bring the columns as the first dimension
    Ap = permute(A,[2 1 3])
    
    %// Per 3D slice offset linear indices
    offset = bsxfun(@plus,[0:M-1]'*N,[0:P-1]*M*N)  %//'
    
    %// Get 3D array linear indices and remove those from permuted array
    Ap(bsxfun(@plus,idx(:),offset)) = []
    
    %// Permute back to get the desired output
    out = permute(reshape(Ap,3,3,3),[2 1 3])
    

    样品运行 -

    >> A
    A(:,:,1) =
         4     4     1     4
         2     9     7     5
         5     9     3     9
    A(:,:,2) =
         4     7     7     2
         9     6     6     9
         3     5     2     2
    A(:,:,3) =
         1     7     5     8
         6     2     9     6
         8     4     2     4
    >> out
    out(:,:,1) =
         4     1     4
         2     9     7
         5     9     9
    out(:,:,2) =
         4     7     2
         9     6     6
         3     5     2
    out(:,:,3) =
         1     5     8
         6     2     9
         8     4     4
    
  • 0

    可以使用下面的linear indexing来完成 . 注意它是's better to work down columns (because of Matlab' s column-major order),这意味着在开头和结尾处进行转置:

    A = [ 1 7 3 4
          1 4 4 6
          2 7 8 9 ];
    v = [2 4 3]; %// the number of elements of v must equal the number of rows of A
    B = A.'; %'// transpose to work down columns
    [m, n] = size(B);
    ind = v + (0:n-1)*m; %// linear index of elements to be removed
    B(ind) = []; %// remove those elements. Returns a vector
    B = reshape(B, m-1, []).'; %'// reshape that vector into a matrix, and transpose back
    

相关问题