Split Vector based on indices from another vector
5 views (last 30 days)
Show older comments
I have a vecotr let's say x=1:200 which is 1x200. Now i have another vector let's say y that is for example 10x1 holds the points where I should split on using predefined range. For example, if I want 5 points before y and 10 points after y, so if I have y=[20;50;120], then the output should be like this [15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
[45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
[115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130]
I tried to set y1=y-5, and y2=y+10, then applied
A=x(1,y1:y2)
but always the first subarray is in the output. Is there any way to divide my array without a for loop because the original array is about 500,000 in length. Thanks in advance
0 Comments
Accepted Answer
More Answers (1)
Andrei Bobrov
on 4 Apr 2017
Edited: Andrei Bobrov
on 4 Apr 2017
x = 1:200;
y=[20;50;120];
dy = 16;
z = zeros(size(x));
z(y - 5) = 1;
z(y + 10) = -1;
z1 = cumsum(z);
out = reshape(x(z1 ~= 0),dy,[])';
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!