How to change a sequence of integers?
Show older comments
I am new to Matlab and coming up already with a tricky question. Suppose a sequence of integers
[2 1 3 4 1 1 3 1 2 1 2 2 5 3 2];
that I want to change according to the following rules:
- When there is a one not followed or preceeded by another one, I want to replace the one, the preceeding and following number by the sum of the two numbers around the one.
- If for two given ones, the preceeding and following numbers overlap, I want to add them allogether.
So in my example, I should obtain:
[5 5 5 4 1 1 7 7 7 7 7 2 5 3 2]
The first three numbers turn to be 5 because I add 2 + 3, according to rule 1. The next three numbers 4 1 1 remain unchanged, also according to rule 1. The then coming 5 numbers [3 1 2 1 2] should all be added together, because of rule 2. Lastly, 2 5 3 2 remain unchanged.
I cannot figure out how to do this. Perhaps there is a way of writing a recursive function that picks a one, checks if and how much numbers have to be added from the left and then looks at the right and finally sums the numbers up. Does anyone have a clue? Many thanks in advance
3 Comments
Jan
on 4 Mar 2021
I do not understand your rule 2:
"If for two given ones, the preceeding and following numbers overlap, I want to add them allogether."
"The then coming 5 numbers [3 1 2 1 2] should all be added together"
Adding all together would give 9, not 7. So you do not mean "all together" but: all but the ones. Correct?
What should happen for [2,1,3,1,4,1,5] ? What about the margins?
S H
on 4 Mar 2021
Jan
on 4 Mar 2021
Okay. So I assume you want sequences of [a,1,b,1,c,1,d,...] of any length to be considered.
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!