Paste array a into array c based on the locations in array b
Show older comments
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
Accepted Answer
More Answers (1)
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
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))]
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))
Categories
Find more on Software Development Tools 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!