廖智宇
廖智宇

Reputation: 41

Is there a matlab function for splitting an array for several array?

I want to split an array into several arrays automatically. For example:

a=[1 2 3 4 5 6 7 8 9]
b=[2 5]

Thus, I want to split it to:

c1=[1 2]
c2=[3 4 5]
c3=[6 7 8 9]

How to do it?

Upvotes: 0

Views: 119

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

A simple way is to use mat2cell:

a = [1 2 3 4 5 6 7 8 9];
b = [2 5];
c = mat2cell(a, 1, diff([0 b numel(a)]));

This gives a cell array c containing the subarrays of a:

>> celldisp(c)
c{1} =
     1     2
c{2} =
     3     4     5
c{3} =
     6     7     8     9

Upvotes: 4

Related Questions