How to remove specific elements in a matrix
4 次查看(过去 30 天)
显示 更早的评论
Say I have a matrix
A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15];
which is a 3x5 matrix and I would like to remove the elements in A(1,2), A(2,3), A(3,4). If I only have the indices of what I want to remove in this matrix, how would I go about removing these elements to create A[1 3 4 5;6 7 9 10;11 12 13 15]; which is a 3x4 matrix. In the end, all the rows have the same same number of columns but if I remove elements piece-wise, the matrix becomes 2 rows with 5 columns and 1 row with 4 columns which MATLAB doesn't like. I tried using a logical matrix with the indices but I only get a 1x12 vector of the remaining values. Is there any easy way to do this without, say breaking up the matrix into vectors and removing the elements that way?
0 个评论
回答(2 个)
Walter Roberson
2016-5-3
mask = zeros(size(A));
mask(sub2ind(size(A), [1 2 3], [2 3 4])) = 1;
A_t = A.';
mask_t = mask.';
new_A = reshape(A_t(~mask_t), [4 3]).' ;
You need to work in transpose space to get the columns to "fall" towards the beginning of the column.
0 个评论
Azzi Abdelmalek
2016-5-3
编辑:Azzi Abdelmalek
2016-5-3
ii=[1 2 3]
jj=[2 3 4]
[n,m]=size(A);
B=zeros(n,m-1);
for k=1:n
a=A(k,:);
a(jj(k))=[];
B(k,:)=a
end
1 个评论
Catherine Mohs
2019-1-29
Can you explain to me what exactly you are doing here? What do ii and jj do?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!