How to divide a long vector into several vectors of known length
4 次查看(过去 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?
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!