Select numbers from an array under a specific condition
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!