count and sum element negative in array

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

count and sum element negative in array

shivax
example:

a=[-3,4,5,-8,-9]

i want to sum element negative :

3 + 8+  9 =20

it's possible to do it with a function?





--
Sent from: http://octave.1599824.n4.nabble.com/Octave-General-f1599825.html


Reply | Threaded
Open this post in threaded view
|

Re: count and sum element negative in array

siko1056
On Thu, Sep 20, 2018 at 10:15 AM shivax <[hidden email]> wrote:
example:

a=[-3,4,5,-8,-9]

i want to sum element negative :

3 + 8+  9 =20

it's possible to do it with a function?


In Octave you can make use of logical indexing:

   -sum (a(a<0))

HTH,
Kai 


Reply | Threaded
Open this post in threaded view
|

Re: count and sum element negative in array

shivax
thanks you


if i want to count element !=0

example :   a=[-3,0,4,5,-8,-9,0]

count=5


it's possible to do it  avoid using loop?



--
Sent from: http://octave.1599824.n4.nabble.com/Octave-General-f1599825.html


Reply | Threaded
Open this post in threaded view
|

Re: count and sum element negative in array

siko1056
On Fri, Sep 21, 2018 at 1:20 AM shivax <[hidden email]> wrote:
thanks you


if i want to count element !=0

example :   a=[-3,0,4,5,-8,-9,0]

count=5


it's possible to do it  avoid using loop?


Sure, use the same technique, I showed in the last post.  Simply express what you want to filter and create a logical index vector:

>> a=[-3,0,4,5,-8,-9,0]
a =

  -3   0   4   5  -8  -9   0

>> a != 0
ans =

  1  0  1  1  1  1  0

This last index vector can be used in turn to access specific elements from "a", namely those, whose index is "1".  Those entries with "0" index are "removed" from "a" in the following expression, note that they aren't deleted from "a" actually.

>> a(a != 0)
ans =

  -3   4   5  -8  -9

And finally you can sumup your items of interest or count the number of "1"s in the index vector:

>> sum (a(a != 0))
ans = -11
>> count = sum (a != 0)
count =  5

The story is always the same with "a != 0", "a >= 0", "a < b", .......  and you can avoid loops easily.

HTH,
Kai



Reply | Threaded
Open this post in threaded view
|

Re: count and sum element negative in array

shivax