MATLAB Answers

# How to get sum of a range

92 views (last 30 days)
Crystal Lee on 12 Aug 2018
Commented: Paolo on 12 Aug 2018
I am trying to get the code below to output the number of elements within v(a vector) that are below 2 and above 4.
sum(sum(v<2 & v>4))
When I define v and run this, it does not work as I would like it to. eg for
v=[1,3,5];
sum(sum(v<2 & v>4))
I am expecting an output of 2, since there is 1 element below 2(1), and 1 element above 4(5).

#### 0 Comments

Sign in to comment.

### Accepted Answer

Paolo on 12 Aug 2018
You want to use the OR operator here and not the AND. Use:
nnz(v<2 | v>4)

#### 2 Comments

Image Analyst on 12 Aug 2018
To build on that, it's because no one number can be both below 2 AND above 4 at the same time. It can be below, or be above, but not both.
Paolo on 12 Aug 2018
That really goes without saying, I am sure OP understands that. He is probably confused about the meaning of logical operators.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!

Translated by