Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
Negar
Negar le 20 Jan 2015
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?

Réponse acceptée

Mohammad Abouali
Mohammad Abouali le 20 Jan 2015
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
  2 commentaires
Negar
Negar le 20 Jan 2015
Thank you so much for nice and easy explanation!
Mohammad Abouali
Mohammad Abouali le 20 Jan 2015
you are welcome. ( ghabel nadare ;) )

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by