Generating index from end and start index

조회 수: 49 (최근 30일)
Benoît Valley
Benoît Valley 2012년 9월 10일
I am looking for an efficient way to do the following (without a loop so that large array can be handled efficiently). Any idea ?
A=rand(1,30) % some data from which I want to extract a subset
s=[1 5 10 22]; % start indexes of the subsets I want to extract
e=[3 7 17 25]; % end indexes of the subset I want to extract
R=[];
for i=1:length(s)
R=[R [s(i):e(i)]];
end
S=A(R); % the answer I am looking for, i.e. the subset of data I want to
% extract
  댓글 수: 1
per isakson
per isakson 2012년 9월 10일
편집: per isakson 2012년 9월 10일
  1. Did you analyze your code with the function, profile?
  2. Which version of Matlab do you use?

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

채택된 답변

Matt Fig
Matt Fig 2012년 9월 10일
If you don't want to use a mex file, this is very fast:
% Make your index into A
L = length(s);
F = cumsum(e-s+1);
idx = ones(1,F(end));
idx(1) = s(1);
idx(1+F(1:L-1)) = s(2:L)-e(1:L-1);
idx = cumsum(idx);
% Now use it as you need:
S = A(idx);

추가 답변 (2개)

Oleg Komarov
Oleg Komarov 2012년 9월 10일
I recommend the nice submission by Bruno Luong: multiple colon.
Use the mex routine, very fast and reliable.

Azzi Abdelmalek
Azzi Abdelmalek 2012년 9월 10일
A=rand(1,30) ;
s=[1 5 10 22];
e=[3 7 17 25];
l=repmat(1:4,2,1);
idx=eval(['[' sprintf('s(%d):e(%d) ',l(:)') ']'])
S=A(idx)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by