Converting values to 0 and 1 and then counting occurrences!
Show older comments
Hello, I am stuck with a problem.
I have a 200x1 matrix containing values ranging from 0 to 30.
Now I want to convert the values which are less than 20 to zero and values greater than zero to 1.
After doing that I want to count how many occurrences are there when 1 is followed by zero and give the counting as an output!
1 Comment
adi kul
on 26 May 2015
Accepted Answer
More Answers (3)
Sebastian Castro
on 26 May 2015
Edited: Sebastian Castro
on 26 May 2015
Suppose your original data is named x. The following line will create a matrix the same size as your original, where the elements are 1 if the logical condition is met and 0 otherwise:
xThresh = x>=20
Then, you can use the diff function to get the difference between consecutive elements. You know that a transition from 1 to 0 is a difference of -1, so you can find all the -1s and add them up:
xDiff = diff(xThresh)
numTransitions = sum(xDiff==-1)
- Sebastian
2 Comments
Image Analyst
on 26 May 2015
I recommend (and voted for) Sebastian's straightforward single-step way, over the other two 2-step solutions offered, though they will also work. In addition to being shorter and more direct, this thresholding method doesn't change your original matrix.
To process a bunch of files, like 5 mat files, use one of the two code snippets in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
adi kul
on 27 May 2015
Andrei Bobrov
on 26 May 2015
Edited: Andrei Bobrov
on 27 May 2015
out = numel(strfind(A(:)' >= 20,[1, 0]));
Ingrid
on 26 May 2015
is this what you mean as it is not clear to what end you would like to do this
x(x<20) = 0;
x(x>=20) = 1;
temp = diff(x);
answer = sum(temp == -1);
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!