Select numbers from an array under a specific condition

조회 수: 17 (최근 30일)
Masato Koizumi
Masato Koizumi 2018년 4월 1일
댓글: Masato Koizumi 2018년 4월 2일
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

채택된 답변

Axel Kottgen
Axel Kottgen 2018년 4월 1일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by