How to split a matrix based on indexing
6 次查看(过去 30 天)
显示 更早的评论
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.
1 个评论
per isakson
2016-6-30
"Data1, Data2, Data3"   usually triggers a link to   How can I create variables A1, A2,...,A10 in a loop?
采纳的回答
per isakson
2016-6-30
编辑:per isakson
2016-6-30
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!