- anything less than -0.5 in test (or more technically, anything in the interval [-Inf, -0.5) in test) to be 1 in the result
- anything in the interval [-0.5, 0.5) in test to be 4 in the result
- anything in the interval [0.5, 3) in test to be 9 in the result
- anything greater than or equal to 3 in test (in the interval [3, Inf]) to be 16 in the result
- and everything else (the NaN values) to be NaN.
Replacing Values in Matrix that are not equal to 1 while excluding 'NaN'
조회 수: 1 (최근 30일)
이전 댓글 표시
I have a globally gridded 3D matrix of air temperature where the 'z' dimension is time. I need to convert all values within the matrix to 1 or 0 depending on whether the values are above or below 0. All temperature values that would fall over water are missing and have been replaced with NaN. I use the following lines to convert the matrix to 1's and 0's, but it also converts the NaN's to 0. I don't want this to happen.
This is currently what I have:
temp_final_1(temp_final_1 > set_point) = 1;
temp_final_1(temp_final_1 ~= 1) = 0;
I tried this, but get an error: "Operands to the logical and (&&) and or (||) operators must be convertible to logical scalar values."
temp_final_1(temp_final_1 > set_point) = 1;
temp_final_1(temp_final_1 ~= 1 && ~isnan(temp_final_1)) = 0;
For example, this is what I am trying to accomplish. The actual values are much more varied than this.
Test1 is before values are changed to 0 or 1 if they are below or above 0 and Test2 shows this with the NaN's still intact
test1 =
NaN 2 9 2
-.23 NaN 3 2
-1 -1 NaN 6
-.4 -1 -.57 NaN
test2 =
NaN 1 1 1
0 NaN 1 1
0 0 NaN 1
0 0 0 NaN
댓글 수: 0
답변 (3개)
Steven Lord
2022년 8월 3일
There are a couple different approaches you can use. With just one dividing level I'd probably just use two logical operations as @David Hill and @Les Beckham did. But if there were multiple levels I'd consider using discretize.
test = [
NaN 2 9 2
-.23 NaN 3 2
-1 -1 NaN 6
-.4 -1 -.57 NaN]
Let's make:
I've added spaces to resultValues below to put the replacement values below the comma separating the two ends of the intervals whose values will be replaced by those values.
intervalEdges = [-Inf, -0.5, 0.5, 3, Inf];
resultValues = [ 1, 4, 9, 16];
result = discretize(test, intervalEdges, resultValues)
David Hill
2022년 8월 2일
test2=test1;
test2(test2==2)=1;
test2(test2<0)=0;
댓글 수: 3
David Hill
2022년 8월 2일
편집: David Hill
2022년 8월 2일
test1 =[NaN 2 9 2
-.23 NaN 3 2
-1 -1 NaN 6
-.4 -1 -.57 NaN];
test2=test1;
test2(test2<=0)=0;
test2(test2>0)=1
Les Beckham
2022년 8월 2일
test1 = [
NaN 2 9 2
-.23 NaN 3 2
-1 -1 NaN 6
-.4 -1 -.57 NaN]
test2 = test1;
test2(test1 > 0) = 1;
test2(test1 < 0) = 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!