heretoinfinity
heretoinfinity

Reputation: 1736

Matlab: change vector values based on if-else condition on the same vector

I have a threshold requirement and would like to round values of a vector to 0 or 1. I don't need to save the old values of the vector

I saw, in the link below, that I could use the following to change the all values of 0 in the s vector to -1 with s( s==0 )=-1; or in general vector(if condition) = desiredValue.

This is better than using a for loop and having an enclosed if condition. What if I would like to include another condition: to change all values greater than 0.8 to 1? Would I have to add another line of code:s( s>=0.8 )=1; or is there a way of checking the two conditions by traversing the vector just once? I only know of using a for loop with an enclosed if-else condition but would like a shorter version if one exists.

https://www.mathworks.com/matlabcentral/newsreader/view_thread/158413

The only related link I found was for R but I am not working with it: Change vector value based on value in same vector

Upvotes: 0

Views: 223

Answers (1)

Xiangrui Li
Xiangrui Li

Reputation: 2426

Matlab allows so-called logical indexing, which is really efficient. To understand what

s(s>0.8) = 1;

does, you can check it with two steps:

ind = s>0.8;

Here ind is a logical array with the same size as s, and has true (1) at locations where s is greater than 0.8, and false (0) otherwise.

s(ind) = 1;

will assign s to 1 at locations where ind is true, while not touching those where ind is false.

To make this easy to understand, you can do this:

ind = find(ind);

This will return those indices for s>0.8. Then you do

s(ind) = 1; 

The logical indexing allows you to skip find, which makes the code simpler and much faster.

To change to different values (-1 and 1 in your example), you need two command for the assignment.

Upvotes: 2

Related Questions