Select numbers from an array under a specific condition
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Masato Koizumi
le 1 Avr 2018
Commenté : Masato Koizumi
le 2 Avr 2018
Dear MATLAB Experts,
Hello. I was curious if I could request for an advice in constructing a program that does the following calculation.
I currently have an array A which contains random integers in numerical order. A = [1 2 4 5 7 9 11 12 13 14 18 23 26 28 32 33 36 37 38 40];
Starting from the first value of array A, I would like to select only the values from A where the selected values are spaced at least 4 numbers. That is, I would like to ultimately obtain A = [1 5 11 18 23 28 33 38] where the selected values from A are such that the numbers between have distances of at least 4.
I would greatly appreciate if you could provide me with any hints in programming this calculation. I am thinking of doing a while loop but having trouble where to start.
Thank you.
Sincerely,
Masato
0 commentaires
Réponse acceptée
Axel Kottgen
le 1 Avr 2018
Hi,
You can do a for loop, followed by if to test if the current number in the loop is at least 4 units higher. If that is the case, you save the current number in the loop to a new array (B in my code) which will store your values. I used a variable "c" to store the last saved number, however you could use the last number of B: c=B(length(B))
It gives the current code, with the initial conditions setup:
B=A(1);
c=A(1);
for i=1:length(A)-1,
if c+4<=A(i+1),
B=[B A(i+1)];
c=A(i+1);
end;
end
Note your initial result in your post was incorrect, correct one is here:
B =
1 5 9 13 18 23 28 32 36 40
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!