How to set -0.0000 and 0.0000 as zero in matlab?

11 次查看(过去 30 天)
By a long calculation I get this array
A1 =
Columns 1 through 13
-0.0000 0.2825 -0.0000 -0.4251 0.0000 1.8665 -0.0000 -0.4917 -0.0000 -1.2564 -3.0573 0.0000 0.9482
Columns 14 through 24
-0.0000 -0.0000 -0.1321 1.8201 -1.2423 -0.0000 0.5664 -0.0000 0.0816 -0.6590 -0.0000
I want to change each element that is greater than zero as 1, smaller than zero as -1 and zero remains zero but matlab is cosnidering 0.0000 and -0.0000 as 1 too. Like this
Z = -(A1<0) + (A1>0)
Z =
Columns 1 through 21
-1 1 -1 -1 1 1 -1 -1 -1 -1 -1 1 1 -1 -1 -1 1 -1 -1 1 -1
Columns 22 through 24
1 -1 -1
Is there a way to keep zeros as zeros? Please help

采纳的回答

Stephen23
Stephen23 2023-3-17
编辑:Stephen23 2023-3-17
"Is there a way to keep zeros as zeros? "
Zeros are zeros.
But the data you show are not zero: the trailing digits tell us that those values are not zero. Compare:
V = [0,eps(0),pi,-pi] % zero and not-zero and +pi and -pi
V = 1×4
0 0.0000 3.1416 -3.1416
Is the 1st value zero? Yes (note no trailing digits).
Is the 2nd value zero? No (the trailing digits tell us this).
So the answer is very clear, that you need to take into account that those values are not zero.
For example, use a tolerance:
tol = 1e-5;
Z = (V>tol)-(V<-tol)
Z = 1×4
0 0 1 -1
or use ROUND beforehand:
W = round(V,5) % look, those are *exactly* zero!
W = 1×4
0 0 3.1416 -3.1416
Z = (W>0)-(W<0)
Z = 1×4
0 0 1 -1

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by