Fill array between values

8 次查看(过去 30 天)
J PARK
J PARK 2021-7-28
评论: J PARK 2021-7-28
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.

采纳的回答

Chunru
Chunru 2021-7-28
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 个评论
Chunru
Chunru 2021-7-28
Then in second row, you have nested pair.
J PARK
J PARK 2021-7-28
Umm..
If 1 or 2 duplicates, I want to use first 1 and last 2.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by