extending a set of rows from matrix using calculated vector of start and end indexes

1 view (last 30 days)
How can I calculate start and end indices "startAndEndIndex" and extract all rows of test matrix "testMatrix" between the the start and index?
Example is the 100x100 matrix below and I have calculated the start index "startindex" (here [1 1 1 5 5 5 9 9 9 13 13 13 17 17 17]) and the end index is "startIndex+3" (here [4 4 4 8 8 8 12 12 12 16 16 16 20 20 20]). So the matrix containign start and end is "startAndEndIndex" matrix below.
What I want is to extract rows 1:4 of "testMatrix" for the first 3 rows in "startAndEndIndex", rows 5:8 of "testMatrix" for the second 3 rows in "startAndEndIndex" and so forth. The results would be in assigned to a new matrix (here it would be a 15 row and 3 column matrix).
startAndEndIndex =
1,4
1,4
1,4
5,8
5,8
5,8
9,12
9, 12
9, 12
13, 16
13, 16
13, 16
17, 20
17, 20
17, 20
%sample code
testMatrix = magic(100);
indexStartt_matrix =repmat(1+4*(0:5-1), 3, 1);
startindex = indexStartt_matrix(:);
startAndEndIndex=[startindex,startindex+3];
startAndEndIndex

Answers (1)

Bruno Luong
Bruno Luong on 3 Sep 2020
testMatrix = magic(100);
indexStartt_matrix =repmat(1+4*(0:5-1), 3, 1);
startindex = indexStartt_matrix(:);
startAndEndIndex=[startindex,startindex+3];
col=arrayfun(@(k) (startAndEndIndex(k,1):startAndEndIndex(k,2))', ...
1:size(startAndEndIndex,1),'unif',0);
col = cell2mat(col);
row=repmat(1:size(col,2),size(col,1),1);
extractMatrix = testMatrix(sub2ind(size(testMatrix),row,col)).'

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!