简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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