Replace values within a range to zero

조회 수: 146 (최근 30일)
Edward Keavney
Edward Keavney 2022년 7월 28일
댓글: Steven Lord 2022년 7월 28일
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
Walter Roberson
Walter Roberson 2022년 7월 28일
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.
Edward Keavney
Edward Keavney 2022년 7월 28일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

sudobash
sudobash 2022년 7월 28일
편집: sudobash 2022년 7월 28일
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
Steven Lord
Steven Lord 2022년 7월 28일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by