How to create time windows given start and stop indices

조회 수: 8 (최근 30일)
Anas Khan
Anas Khan 2022년 11월 10일
댓글: Image Analyst 2022년 11월 10일
I have 2 vectors of indices: 1 for start times and 1 for end times:
>> size(trainStarts)
ans =
20 1
>> size(trainEnds)
ans =
20 1
Is there a way to, without using loops, that I can create a new variable representing windows that would be like trainStarts(1) : trainEnds(1), trainStarts(2) : trainEnds(2) and so on?

채택된 답변

Voss
Voss 2022년 11월 10일
Here's one way:
trainStarts = [2 10 15];
trainEnds = [6 12 21];
result = arrayfun(@(x,y)x:y,trainStarts,trainEnds,'UniformOutput',false)
result = 1×3 cell array
{[2 3 4 5 6]} {[10 11 12]} {[15 16 17 18 19 20 21]}

추가 답변 (1개)

Image Analyst
Image Analyst 2022년 11월 10일
편집: Image Analyst 2022년 11월 10일
Yes, but why? What's wrong with having them in separate arrays.
for k = 1 : length(trainStarts)
thisRange = trainStarts(k) : trainEnds(k);
% Now do something with thisRange.
end
If you want to store/keep all the ranges separately you need to put them into cells because each range might be a different number of elements.
for k = 1 : length(trainStarts)
thisRange{k} = trainStarts(k) : trainEnds(k);
% Now do something with thisRange.
end
If you don't know what a cell array is see the FAQ:
  댓글 수: 2
Anas Khan
Anas Khan 2022년 11월 10일
Thanks, yeah, I may not need to keep the ranges. I was just trying to keep the code as clean as possible for downstream analysis.
Image Analyst
Image Analyst 2022년 11월 10일
Then use my first snippet rather than my second snippet or the answer you Accepted. No sense storing stuff you don't need to store.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by