help-octave
[Top][All Lists]

## Re: count and sum element negative in array

 From: Kai Torben Ohlhus Subject: Re: count and sum element negative in array Date: Fri, 21 Sep 2018 09:44:24 +0200

On Fri, Sep 21, 2018 at 1:20 AM shivax <address@hidden> 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