Clear Filters
Clear Filters

Fill array between values

8 views (last 30 days)
J PARK
J PARK on 28 Jul 2021
Commented: J PARK on 28 Jul 2021
I have an array like this.
0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 2 0 2 0 0 0 0 0 0
0 0 0 0 0 0 1 0 2 0 1 0 2 0 0 0 0 0 0 0
I'd like to fill 3 between 1 and 2, like this.
0 0 0 0 0 0 1 3 3 3 3 3 2 0 0 0 0 0 0 0
0 0 0 0 0 1 3 3 1 3 3 2 3 2 0 0 0 0 0 0
0 0 0 0 0 0 1 3 2 0 1 3 2 0 0 0 0 0 0 0
Is there any way to solve this?
I can't find function to do so.

Accepted Answer

Chunru
Chunru on 28 Jul 2021
The rule is not clear in your question. In first/second row, you fill 3 between first 1 and last 2. In third row, you fille 3 between 2 pairs of 1 and 2.
The code below assume the rule is to fill 3 between 1st 1 and last 2. You can change the code to fit the rule you set.
A =[0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 1 0 0 2 0 2 0 0 0 0 0 0
0 0 0 0 0 0 1 0 2 0 1 0 2 0 0 0 0 0 0 0];
for i=1:size(A,1)
i1 = find(A(i,:)==1, 1, 'first');
i2 = find(A(i,:)==2, 1, 'last');
i0 = find(A(i,i1:i2) == 0);
A(i, i1-1 + i0) = 3;
end
A
A = 3×20
0 0 0 0 0 0 1 3 3 3 3 3 2 0 0 0 0 0 0 0 0 0 0 0 0 1 3 3 1 3 3 2 3 2 0 0 0 0 0 0 0 0 0 0 0 0 1 3 2 3 1 3 2 0 0 0 0 0 0 0
  3 Comments
Chunru
Chunru on 28 Jul 2021
Then in second row, you have nested pair.
J PARK
J PARK on 28 Jul 2021
Umm..
If 1 or 2 duplicates, I want to use first 1 and last 2.

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!