简体   繁体   English

MATLAB仅从矩阵中删除某些零

[英]MATLAB Remove Only Certain Zeros from Matrix

I have seen plenty of answers regarding how to remove leading and/or trailing zeros, and how to remove all zeros from a vector or matrix. 关于如何删除前导和/或尾随零以及如何从矢量或矩阵中删除所有零,我已经看到了很多答案。 What I need to do, though, is only remove some of them. 不过,我只需要删除其中一些即可。 I have two matrices, and I only want to remove the entries where both of them are zero. 我有两个矩阵,我只想删除两个均为零的条目。 They are two-dimensional x and y coordinates, solved using characteristics (I can give more detail if needed) and I just want to remove the values where both matrices contain zeros at the same indices. 它们是二维x和y坐标,可以使用特征来解决(我可以在需要时提供更多详细信息),而我只想删除两个矩阵在相同索引处均包含零的值。 I can easily convert the matrices into vectors and work with vectors, so any help in either case would be greatly appreciated. 我可以轻松地将矩阵转换为向量并可以使用向量,因此无论哪种情况,我们都将不胜感激。

For the sake of simplicity, let's assume you're using vectors called X and Y (of the same length), and you want to remove only those entries where both vectors are zero. 为了简单起见,假设您使用的向量称为XY (具有相同的长度),并且只想删除两个向量均为零的那些条目。 Here's how (not tested): 方法如下(未经测试):

% Find the indexes where either X or Y is different from zero
% (these are the indexes of the components we want to keep)
I = find(X~=0 | Y~=0);

% Select the desired components from X and Y
X=X(I);
Y=Y(I);

Edit: As Oli has pointed out below (and stefano explained further), you should use logical indexing for better performance. 编辑:正如Oli在下面指出的(以及stefano进一步说明),您应该使用逻辑索引来获得更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM