Hi. I'm trying to find the consecutive values sorted in a vector and count the total number of the consecutive values. Here is what I have:
A = input('Enter a vector: ');
diff(find(diff([nan A nan])~=1));
% By entering the vector [1 2 3 4 4 4 3 2 1], the output would be
% ans =
% 4 1 1 1 1 1
The reason I'm stuck is that my code only works for increment vectors([1 2 3 4]), but not for identical([4 4 4]) or decrement vectors([4 3 2 1]). Any suggestions or hints will be of great help to me.
Thank you for replying. I'm trying to write a code to find consecutive values are sorted, neither increasing nor decreasing, and I want to write one code that satisfies both conditions, and that's where I get stuck.
Yeah, what do you do in a situation like this? The 0 could be a member of the consecutive decreasing sequence (4,3,2,1,0) but also a member of the increasing sequence (0,1,2,3,4,5). So do you want to count the 0 twice -- once in each group? Or just in the first group? So would the result be
4 for the 1,2,3,4
1 for going from the first 4 to the second 4 which doesn't increase or decrease by 1
1 for going from second 4 to the third 4 which doesn't increase or decrease by 1
5 for the decreasing sequence [4,3,2,1,0] (which starts with the third 4)
6 for the increasing sequence [0,1,2,3,4,5] or 5 if you didn't want to include the 0 again.
So that would give a result of [4,1,1,5,6].
I guess, Peter, we'd need a better explanation of your rules. Also, can we assume that the numbers area strictly integers, and that this is not your homework?
I don't understand why you said
A = input('Enter a vector: ');
diff(find(diff([nan A nan])~=1));
% By entering the vector [1 2 3 4 4 4 3 2 1], the output would be
% ans =
% 4 1 1 1 1 1
I can see the first 4, and maybe two of the 1's, but since the tail end of the vector was [4,3,2,1] (4 consecutive numbers) and your code was clearly trying to allow for differences of -1 as well as +1, why is there not a 4 as the last element of your answer?
Impossible de terminer l’action en raison de modifications de la page. Rechargez la page pour voir sa mise à jour.
Translated by
Sélectionner un site web
Choisissez un site web pour accéder au contenu traduit dans votre langue (lorsqu'il est disponible) et voir les événements et les offres locales. D’après votre position, nous vous recommandons de sélectionner la région suivante : .
Vous pouvez également sélectionner un site web dans la liste suivante :
Comment optimiser les performances du site
Pour optimiser les performances du site, sélectionnez la région Chine (en chinois ou en anglais). Les sites de MathWorks pour les autres pays ne sont pas optimisés pour les visites provenant de votre région.