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

3 次查看(过去 30 天)
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?

采纳的回答

Mohammad Abouali
Mohammad Abouali 2015-1-20
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by