Replace values within a range to zero

Hi,
I have an array 26X106 that contains both positive and negative values.
I want to be able to replace the numbers within a specified range to zero - e.g., all numbers >0.25 and <0.25 are replaced by zero.
Any help would be greatly appreciated,
Thanks!

2 Comments

You only want to keep values that are exactly 0.25? exactly equal is the only value that is not less than and not greater than.
I would like to keep the negative values that are equal or less than -0.025 (i.e., -0.03) and keep the positive values that are equal or greater than 0.025 (e.g., 0.03) - all the values between the range would then be changed to equal zero.

Sign in to comment.

Answers (1)

Hi!
This is how to select numbers from a matrix in a given range.
matr = rand(5)
matr = 5×5
0.5725 0.3692 0.6680 0.1522 0.6984 0.3249 0.3382 0.9941 0.8481 0.4326 0.8804 0.6613 0.0909 0.6754 0.1913 0.6391 0.3758 0.8331 0.7947 0.5164 0.8831 0.9587 0.7263 0.6760 0.8337
mask = matr < 0.25 & matr > -0.25
mask = 5×5 logical array
0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0
Selecting in this manner returns a logical matrix commonly known as a mask matrix. You can then set the values at those locations to 0 like this.
matr(mask) = 0
matr = 5×5
0.5725 0.3692 0.6680 0 0.6984 0.3249 0.3382 0.9941 0.8481 0.4326 0.8804 0.6613 0 0.6754 0 0.6391 0.3758 0.8331 0.7947 0.5164 0.8831 0.9587 0.7263 0.6760 0.8337
Hope this answers your question.
This article talks about some basics of matrix indexing in MATLAB.

1 Comment

You can also do this using the or operator | instead of the and operator &.
x = 1:10;
tooSmall = x < 4
tooSmall = 1×10 logical array
1 1 1 0 0 0 0 0 0 0
tooBig = x > 7
tooBig = 1×10 logical array
0 0 0 0 0 0 0 1 1 1
reject = tooSmall | tooBig
reject = 1×10 logical array
1 1 1 0 0 0 0 1 1 1
keep1 = ~reject % Could also be written
keep1 = 1×10 logical array
0 0 0 1 1 1 1 0 0 0
keep2 = ~tooSmall & ~tooBig % not too small and not too big
keep2 = 1×10 logical array
0 0 0 1 1 1 1 0 0 0
x(reject) % 1, 2, and 3 are too small; 8, 9, and 10 are too big
ans = 1×6
1 2 3 8 9 10
x(keep1) % 4, 5, 6, and 7 are just right
ans = 1×4
4 5 6 7

Sign in to comment.

Products

Release

R2019a

Tags

Asked:

on 28 Jul 2022

Commented:

on 28 Jul 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!