Help in writing a a code for an array based on comdition.

I have an array A. A1= [-0.0082 -0.0409 -0.0175 -0.0853 0.0217 -0.2556 -0.0302 0 ]
From A array I want to replace negative numbers with -1, positive numbers with 1 and zero will remain zero . Like this :
A= [-1 -1 -1 -1 1 -1 -1 0]
Then I want to take there sum and if there sum is smaller than threshold then value will be set to zero. If equals and greater than threshold than value will be 1. Threshold is 12.
How to write code for this?

 Akzeptierte Antwort

A1 = [-0.0082 -0.0409 -0.0175 -0.0853 0.0217 -0.2556 -0.0302]
A1 = 1×7
-0.0082 -0.0409 -0.0175 -0.0853 0.0217 -0.2556 -0.0302
A = -(A1<0) + (A1>0)
A = 1×7
-1 -1 -1 -1 1 -1 -1
s = sum(A)
s = -5
threshold = 12;
value = double(s >= threshold)
value = 0

4 Kommentare

How to write zero values as zero in this 'A = -(A1<0) + (A1>0)'?
A1 = -2:2
A1 = 1×5
-2 -1 0 1 2
A = -(A1<0) + (A1>0)
A = 1×5
-1 -1 0 1 1
So the code already leaves 0 as 0.
Haya Ali
Haya Ali am 17 Mär. 2023
Bearbeitet: Haya Ali am 17 Mär. 2023
It is taking 0 as a positive number and -0 as a negative number. Please help
Columns 1 through 13
0.0000 -0.0000 3.2115 2.7009 -0.0000 -0.0000 0.0000 0.1799 0.9524 -0.0000 -0.0000 0.1566 0.0000
Columns 14 through 25
-0.0000 -0.0000 -0.0000 -0.0000 -0.0000 0.0000 -0.0000 0.0000 -0.0000 0.0000 -0.0000 -0.0000
A =
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 25
-1 1 -1 -1
0 and -0 display as 0 not as 0.0000 or -0.0000. So your values are not 0 and -0
Give the command
format long g
and then display your values again

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 17 Mär. 2023

0 Stimmen

See sum sign
However, your description does not match your example. You say you want to replace positive numbers with 1, but your example shows replacing the only positive number with 0.

Kategorien

Mehr zu Data Types finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 17 Mär. 2023

Kommentiert:

am 17 Mär. 2023

Community Treasure Hunt

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

Start Hunting!

Translated by