Using Indexing from values in another vector

조회 수: 2 (최근 30일)
Ryan
Ryan 2013년 9월 22일
Hello all,
I have a vector called i, where for example
i = [1 1 2 3 3]';
and I have a vector n, where
n = [2 1 2]'
corresponds to the number of values in i. So n(1) corresponds to the number of 1's in i, n(2) corresponds to the number of 2's in i, etc. I also have another vector j, where j also has values like
j = [1 3 2 2 3].
My question is how could I use the vector n to access the elements in j? Basically I want to use the first two elements of j since n(1) = 2, then I want to access the second element since n(2) = 1 and finally the last two elements of j since n(3) = 2.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 22일
i = [1 1 2 3 3]';
n = [2 1 2]';
j = [1 3 2 2 3];
idx2= cumsum(n);
idx1=[1; idx2(1:end-1)+1];
for k=1:numel(idx1)
s{k}=j(idx1(k):idx2(k))
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Special Characters에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by