# How to group an array and then replace each group with different numbers?

2 ビュー (過去 30 日間)
Rikke 2019 年 3 月 20 日
コメント済み: Rikke 2019 年 3 月 20 日
Example of array: A = [1 1 1 0 0 0 1 0 0 1 0 1 1 0 0 ];
Wanted array: B = [1 1 1 4 4 4 1 5 5 1 6 1 1 3 3];
Is is possible to separate each group of zeros in A and then replace each group with a number in another array?
First group of zeros is the first three zeros in A, g1=[0, 0, 0];
Second group: g2=[0, 0];
and so on.
Then i want to replace each group with C = [4, 5, 6, 3];
The result will be g1 = [4, 4, 4], g2 = [5, 5] and so on.

### 採用された回答

Andrei Bobrov 2019 年 3 月 20 日
B = A;
B(A==0) = repelem(C,diff(reshape(find(diff([1,A,1]) ~= 0),2,[])));

#### 2 件のコメント

Luna 2019 年 3 月 20 日
+1 for blowing mind!
Rikke 2019 年 3 月 20 日
Brilliant, thank you!

### その他の回答 (1 件)

Luna 2019 年 3 月 20 日
Try this:
A = [1 1 1 0 0 0 1 0 0 1 0 1 1 0 0];
C = [4, 5, 6, 3];
A(end+1) = 1;
locRise = find([0 diff(A == 0) > 0]);
locFall = find([diff(A==0) < 0 0]);
for i = 1:numel(locRise)
A(locRise(i):locFall(i)) = C(i);
end
A(end) = [];
Note: number of groups of zeros should be same with the length of C.

#### 1 件のコメント

Rikke 2019 年 3 月 20 日
Perfect, thank you!