# Paste array a into array c based on the locations in array b

1 view (last 30 days)
Immanuel Heim on 18 Nov 2021
Edited: Stephen23 on 19 Nov 2021
Hello,
i have tow row arrays a = [1 2 3 4 5 6] and b = [1 5 8 14 19 23].
My goal is to paste a in the columns specified in b with overlap:
The output should be c = [ 1 2 3 4 1 2 3 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 5]
1 1
2 2
3 3
4 4
5 5 1
6 6 2
7 3
8 4 1
9 5 2
10 6 3
11 4
12 5
13 6
14 1
15 2
16 3
17 4
18 5
19 6 1
20 2
21 3
22 4
23 5

Stephen23 on 19 Nov 2021
Edited: Stephen23 on 19 Nov 2021
This is robust also when there is no overlap:
a = [1,2,3,4,5,6];
b = [1,5,8,14,19,23];
d = diff(b);
d(end) = d(end)+1; % inconsistent logic
c = nan(1,b(end)); % preallocate
for k = 1:numel(b)-1
x = 1:d(k);
c(b(k)+x-1) = a(x);
end
c
c = 1×23
1 2 3 4 1 2 3 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 5

### More Answers (1)

DGM on 19 Nov 2021
Edited: DGM on 19 Nov 2021
Assuming what you want is a vector, the example doesn't follow the description of the logic and the inputs given. Consider
a = [1 2 3 4 5 6];
b = [1 5 8 14 19 23];
db = diff(b);
c = [];
for k = 2:numel(b)
c = [c a(1:db(k-1))];
end
c
c = 1×22
1 2 3 4 1 2 3 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4
According to b, a new sequence starts at index 23. So either c stops at 4 (at 22 elements long), or it continues for 6 more elements. If you chose to assert that c must be max(b) elements long, then it would terminate with 1. Etiher way, it would be inconsistent for it to stop at 5. If that's the way it must end, then that would have to be accomodated with a change to the logic.
c = [];
for k = 2:numel(b)-1
c = [c a(1:db(k-1))];
end
c = [c a(1:max(b)-numel(c))]
c = 1×23
1 2 3 4 1 2 3 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 5
I'm sure either case could be made more elegant once the details are clarified. For instance, in the aforementioned case where c is max(b) elements long and terminates with the first element of a new sequence:
r = ones(1,max(b));
r(b(2:end)) = 1-diff(b);
c = a(cumsum(r))
c = 1×23
1 2 3 4 1 2 3 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1