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

时间:2015-09-06 22:56:23

标签: arrays matlab matrix vectorization

如何删除矩阵中的元素,这些元素不是一条直线,而不是在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 个答案:

答案 0 :(得分:1)

可以使用以下linear indexing来完成。请注意,最好使用列(因为Matlab的column-major顺序),这意味着在开头和结尾处进行转置:

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

答案 1 :(得分:0)

这是使用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