Split Vector based on indices from another vector

조회 수: 6 (최근 30일)
Sara Mohamed
Sara Mohamed 2017년 4월 4일
편집: Andrei Bobrov 2017년 4월 4일
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

채택된 답변

Thorsten
Thorsten 2017년 4월 4일
편집: Thorsten 2017년 4월 4일
You can generate a cell array where the i'th cell is the desired range for the i'th value in y:
C = arrayfun(@(yi) x(yi-5:yi+10), y, 'UniformOutput', false);
If you want the subarrays as rows of a matrix, use
M = cell2mat(C);

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 4월 4일
편집: Andrei Bobrov 2017년 4월 4일
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,[])';

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by