How do you use multiple indices to separate data and put in a structure?

1 view (last 30 days)
I have a 3672 x10 matrix (A). I have a 1x300 array of indices (B). What I would like to do is get the data in matrix A between the indices in B and put each into a strucure. For example, I would like the first cell in the structure to contain these data:
A(B(1,1):B(1,2)-1,:)
I would like the second cell in the structure to contain these data:
A(B(1,2):B(1,3)-1,:)
I would like the third cell in the structure to contain these data:
A(B(1,3):B(1,4)-1,:)
...and so on thus that the last cell in the structure is
A(B(1,300):end,:)
So the structure will have 300 cells where each cell contains different snippets of data as defined above.

Accepted Answer

the cyclist
the cyclist on 11 May 2020
Edited: the cyclist on 11 May 2020
Here's one straightforward way
% Make up some data and indices
A = rand(3672,10);
B = 1:2:600;
% Preallocate the cell array
C = cell(300,1);
% Assign the cell contents
for ii = 1:299
C{ii} = A(B(1,ii):B(ii+1)-1,:);
end
% Assign the last cell, which is a special case
C{300} = A(B(1,300):end,:);

More Answers (1)

the cyclist
the cyclist on 11 May 2020
I was pretty sure there was a simple vectorized way to do this, but it did not come to me right away. But then I remembered it:
% Make up some data and indices
A = rand(3672,10);
B = 1:2:600;
rowCountByCell = diff([B size(A,1)+1]);
C = mat2cell(A,rowCountByCell);

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!