gbox
gbox

Reputation: 829

How Does Sum Function work?

for the following code:

A = 1:10

For Sum(A) I get 55 which is the sum of the elements values.

But for the following I get:

A = 1:10

For Sum(A<9) I get 8 which is the sum of elements that answer the condition (but not the sum of the values of the elements)

Upvotes: 0

Views: 169

Answers (1)

MattG
MattG

Reputation: 1426

A<9 returns a binary vector with 1s in the position that answer the condition and 0s in the positions that do not. sum(A<9) thus sums a vector containing 8 1s, yielding 8, as expected. You should not be getting 9.

You want:

sum(A(A<9));

to get the sum of the values that meet the condition.

Upvotes: 3

Related Questions