MATLAB: How to divide a long vector into several vectors of known length

for loop

Dear all,
Is there a way to divide a vector into several vectors of known length? lets say my vector is:
IDX = [1 2 1 3 4 3 1 2 1 35 4 2];
and I want it to be splittet into three vectors, each of length equal to numel(a{k}), which a{k} is:
a{k} = {[3 2 2 1 2] [2 1 2 2] [1 2 3 ]}
So, the first vector is to be of length 5, the second vector of length 4, and the last vector of length 3.
I tried the following,
for k = 1: 3
if (k ==1)
idx{k} = IDX(1:numel(a{k})) ;
else
idx{k} = IDX(numel(a{k-1})+1:numel(a{k-1})+ numel(a{k}))
end
end
I wish to see this result:
idx{1} = [1 2 1 3 4], idx{2} = [3 1 2 1] and idx{3}=[35 4 2]
but it seems to only retrieve the first two vectors correctly, and the third one just sucks. Any help please?

Best Answer

IDX = [1 2 1 3 4 3 1 2 1 35 4 2 78];
a = {[3 2 2 1 2] [2 1 2 2] [1 2 3 4]};
% first get the numel(a{k}) as a vector
vectorSizes=cellfun(@(x) numel(x),a)
vectorSizes =
5 4 4
% now split IDX into the vectors we desired length
IDX_splitted=mat2cell(IDX,1,vectorSizes);
% each element of the cell IDX_splitted contains one of the vectors that you desire.
IDX_splitted{1}
ans =
1 2 1 3 4
IDX_splitted{2}
ans =
3 1 2 1
IDX_splitted{3}
ans =
35 4 2 78