How to split a matrix based on indexing

6 views (last 30 days)
I have a matrix (e.g. 16x11 double) that I want to split up into smaller matrices. I have created a index vector of zeros and ones (e.g. 16x1). Every time there is a one, I would like to split the matrix at this point. So if the 1's appear in row 1,5,12 I would need 3 matrices created from the original (so rows 1 to 4, 5 to 11, 12 to end). It would be useful to increment the matrix name too, like Data1, Data2, Data3. I think this needs to be a for loop? I need to repeat this on numerous sets of data with differing amounts of 1's in my index vector.

Accepted Answer

per isakson
per isakson on 30 Jun 2016
Edited: per isakson on 30 Jun 2016
Two ways, arrayfun and for-loop
M = repmat( transpose([1:16]), [1,11] );
ix1 = [1,5,12];
ix2 = [ix1(2:end)-1,size(M,1)];
data = arrayfun( @(r1,r2) M(r1:r2,:), ix1, ix2, 'uni', false );
cac = cell( 1, length(ix1) );
for jj = 1 : length(ix1)
cac{jj} = M(ix1(jj):ix2(jj),:);
end
and check the results
>> data
data =
[4x11 double] [7x11 double] [5x11 double]
>> data{2}
ans =
5 5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10 10
11 11 11 11 11 11 11 11 11 11 11
>>
>> cac
cac =
[4x11 double] [7x11 double] [5x11 double]
>> cac{1}
ans =
1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4

More Answers (0)

Categories

Find more on Multidimensional Arrays 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!