简体   繁体   中英

remove rows of matrix in matlab

If I have a matrix X with only one column and it has some negative values in some rows. How can I remove only the negative values?

Example:

X=[-1; 2; 3; -4; 5]

should become:

X=[2; 3; 5]

Also, how can I remove values from

y=[1; 2; 3; 4; 5]

based on where the negative values in X are found? y should be [2; 3; 5] [2; 3; 5] [2; 3; 5] after this operation.

Removing negative values from X :

You can either reassign X to a vector which only contains the values of X which are not negative:

>> X = X(X>=0)
X =
     2
     3
     5

or delete the negative values from X :

>> X(X<0) = []
X =
     2
     3
     5

Removing values from y based on the indices of negative values in X is similar. Either reassign:

>> y = y(X>=0)
y =
     2
     3
     5

Or delete:

>> y(X<0) = []      
y =
     2
     3
     5

If you want to modify both vectors based on the negative values in X remember to do the operation to y first or store a logical vector for the positions where X<0 . For example:

>> ind = X < 0;
>> X(ind) = []
X =
     2
     3
     5
>> y(ind) = []
y =
     2
     3
     5

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