Composer
Composer

Reputation: 255

Remove values from a vector based on restriction

If i have a vector (array) in matlab, is it possible to remove the values from that vector based on some restriction (e.g.. all non negative numbers).

Can you please advise me on the best approach to do that.

Upvotes: 1

Views: 262

Answers (2)

timgeb
timgeb

Reputation: 78650

Yes, you can either use logical indexing to keep the values which meet a criterion or use the find function to get the indexes which hold values that meet a criterion.

logical indexing

the find function

An example of logical indexing where we want to remove all the values from a vector which are not greater than three:

>> x=[1,2,3,4,5,6]
x =
     1     2     3     4     5     6
>> x=x(x>3) 
x =
     4     5     6

You can also ask for multiple criteria as you would expect. In the following example, we want to keep every value which is greater than three, but not five.

>> x=[1,2,3,4,5,6]
x =
     1     2     3     4     5     6
>> x=x(x>3 & x~=5)
x =
     4     6

Finally, the find function can come in handy when you need the indexes of values which meet a criterion.

>> x=[1,1,2,2,5,5]
x =
     1     1     2     2     5     5
>> ind=find(x>3)
ind =
     5     6

Logical indexing and find can also be applied to matrices with more than one row/column. Thanks @Alan for helping me improve the answer.

Upvotes: 4

Alan
Alan

Reputation: 3417

You may want to look into logical indexing, as it neatly handles your problem.

To use the example you gave, if you have a vector a of numbers, and you want to remove all negative numbers you could do the following:

b = a(a >= 0);

which would create a vector b containing only the positive elements of a, or you could try:

a(a < 0) = [];

would set any elements in the vector a to []

Upvotes: 2

Related Questions