MATLAB Answers

# How can I count the number of times a specific value appears within a range in a 1D vector?

1 view (last 30 days)
Caesar Hernandez on 27 Apr 2020
Commented: per isakson on 29 Apr 2020
Given a 1D vector, x, that has 600000 elements, how can I count the number of times the value 1 appears after the 150th position (excluding 150)?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Daniel M on 27 Apr 2020
sum(x(151:end) == 1)
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### More Answers (2)

Ameer Hamza on 27 Apr 2020
Edited: Ameer Hamza on 27 Apr 2020
Try this.
x = randi([1 10], 1, 600000); % random vector
result = sum(x(151:end)==1);
##### 1 CommentShowHide None
Caesar Hernandez on 29 Apr 2020
This also worked.

Sign in to comment.

per isakson on 27 Apr 2020
If x is a vector of whole numbers
sum( double( x(151:end)==1 ) )
else
sum( double( abs(x(151:end)-1) < small_number ) )
##### 2 CommentsShowHide 1 older comment
per isakson on 29 Apr 2020
It works here. Did it return any error message?

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!