필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Negar
Negar 2015년 1월 20일
댓글: Mohammad Abouali 2015년 1월 20일
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
  댓글 수: 2
Negar
Negar 2015년 1월 20일
Thank you so much for nice and easy explanation!
Mohammad Abouali
Mohammad Abouali 2015년 1월 20일
you are welcome. ( ghabel nadare ;) )

댓글을 달려면 로그인하십시오.

추가 답변 (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