# Split an array using specific points

6 views (last 30 days)
Daniel Adeniyi on 1 Mar 2022
Commented: Stephen23 on 26 Apr 2022
Just starting out in matlab and would appreciate your help.
for example : lets say I have an array Y = [5;2;3;6;7;9;5;5;6;3;8;7;74;9;63;47;10;3]; and another array of index diiv = [5;9;15];
How can i use diiv to break Y into smaller arrays so I would get as output arrays y1 = [5;2;3;6;7], y2 =[9;5;5;6]; y3 =[3;8;7;74;9;63]; y4=[47;10;3]
Thanks
Stephen23 on 2 Mar 2022
If you are numbering your variables like that then you are doing something wrong.
If you are trying to access variable names dynamically then you are doing something wrong.
Simple and efficient MATLAB code uses arrays and indexing. You should use arrays and indexing.

Stephen23 on 2 Mar 2022
Edited: Stephen23 on 2 Mar 2022
Simpler and more efficient than what you are attempting (although most likely you don't realise that yet):
Y = [5;2;3;6;7;9;5;5;6;3;8;7;74;9;63;47;10;3];
diiv = [5;9;15];
D = diff([0;diiv;numel(Y)]); % complete the missing data
C = mat2cell(Y,D,1) % split into a cell array
C = 4×1 cell array
{5×1 double} {4×1 double} {6×1 double} {3×1 double}
C{:}
ans = 5×1
5 2 3 6 7
ans = 4×1
9 5 5 6
ans = 6×1
3 8 7 74 9 63
ans = 3×1
47 10 3
##### 2 CommentsShowHide 1 older comment
Stephen23 on 26 Apr 2022

Alan Stevens on 1 Mar 2022
Like this?
Y = [5;2;3;6;7;9;5;5;6;3;8;7;74;9;63;47;10;3];
diiv = [5; 9; 15];
y1 = Y(1:diiv(1));
y2 = Y(diiv(1)+1:diiv(2));
y3 = Y(diiv(2)+1:diiv(3));
y4 = Y(diiv(3)+1:end);
##### 2 CommentsShowHide 1 older comment
Stephen23 on 2 Mar 2022
"is it possible to do this automatically (like in a loop) without writing out each expression for y1, y2,y3,y4"
It is certainly possible, but only if you want to force yourself into writing slow, complex, inefficient code which is buggy and hard to debug:
In contrast the neat, simple, and very efficient MATLAB approach is to use indexing.
Tip: if you are numbering your varaible names like that, then you are doing something wrong.

Matt J on 1 Mar 2022
More likely you would want to do something like this,
y=mat2cell(Y,diiv)
Daniel Adeniyi on 2 Mar 2022
this gives a dimension error unfortunately as the sum of the elements in diiv is greater than the number of elements in Y.