Converting values to 0 and 1 and then counting occurrences!
Mostra commenti meno recenti
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 Commento
adi kul
il 26 Mag 2015
Risposta accettata
Più risposte (3)
Sebastian Castro
il 26 Mag 2015
Modificato: Sebastian Castro
il 26 Mag 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 Commenti
Image Analyst
il 26 Mag 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
il 27 Mag 2015
Andrei Bobrov
il 26 Mag 2015
Modificato: Andrei Bobrov
il 27 Mag 2015
out = numel(strfind(A(:)' >= 20,[1, 0]));
Ingrid
il 26 Mag 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);
Categorie
Scopri di più su Data Import and Analysis in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!