0

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
廖智宇
  • 21
  • 5

1 Answers1

4

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • I got it, thank you for you help! – 廖智宇 Apr 04 '22 at 13:05
  • Hello, I have another question. If I want to convert cell to array, how to do it? I look forward to hearing you, thank you! – 廖智宇 Apr 05 '22 at 15:28
  • @廖智宇 Sorry, I'm not sure I understand what you mean. In my code, `c` is a [cell array](https://www.mathworks.com/help/matlab/cell-arrays.html). You can access the individual pieces of your original array with curly-brace indexing: `c{1}` etc. Does that help? – Luis Mendo Apr 05 '22 at 15:38
  • Thank you for your reply. I know how to access cell array. But I want to achieve like c1=[1 2]. Now I solved it, thank you! – 廖智宇 Apr 05 '22 at 15:47
  • BTW, I have another question about array. b=[2 5]; c1=[1 2]; c2=[3 4 5]; c3=[6 7 8 9]; Since b(1,1) and b(1,2) belong to c1 and c2, how can I get it by MATLAB function? I look forward to hearing you, thank you! – 廖智宇 Apr 05 '22 at 15:50
  • @廖智宇 You probably want [`ismember`](https://www.mathworks.com/help/matlab/ref/double.ismember.html). Not also that dynamic variables (such as `c1`, `c2` instead of a cell array `c`) are almost always [not a good idea](https://stackoverflow.com/a/32467170/2586922) – Luis Mendo Apr 05 '22 at 22:37