Select numbers from an array under a specific condition

8 ビュー (過去 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
  1 件のコメント
Masato Koizumi
Masato Koizumi 2018 年 4 月 2 日
Thank you Axel Kottgen!! I deeply appreciate your help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by