Convert matlab index vector to 2D array based on gaps

Hi all,
I am asking to get feedback on my code and see if there are other ways to programme this basic algorithm more efficiently or elegantly.
out = segments([1 end]); % Start point of first interval
for idx = find(diff(segments) > 1) % Iterate over gaps
out(end, 2) = segments(idx); % End point of current interval
out(end + 1, 1) = segments(idx + 1); % Start point of next interval
end
out(end, 2) = segments(end); % End point of last interval
out(:, diff(out, [], 2) == 0) = []; % Remove point intervals
E.g., for segments = [12 13 14 16 17 18], the output out = [12 14; 16 18] noting the gap between 14 and 16.

 채택된 답변

You can vectorize the code -
seg = [12 13 14 16 17 18 20 21 22 23 24];
idx = diff(seg)~=1;
out = [seg(1) seg([false idx]); seg([idx false]) seg(end)].'
out = 3×2
12 14 16 18 20 24

댓글 수: 4

This is genius!
It took me a few minutes to understand but i think it effectively conveys the first row having all the "start" indices and the second row having all the end indices.
Is there a reason why the transpose is written as .' instead of just '?
Dyuman Joshi
Dyuman Joshi 2023년 12월 21일
편집: Dyuman Joshi 2023년 12월 21일
Yes, that's it!
As for the tranpose, it's a habit. Since we are dealing with real numbers, .' is equal to ' . So you can use either of them here.
Updated code -
seg = [12 13 14 16 17 18 20 21 22 23 24];
idx = diff(seg)~=1;
out = [seg([true idx]); seg([idx true])].'
out = 3×2
12 14 16 18 20 24
Stephen23
Stephen23 2023년 12월 24일
편집: Stephen23 2023년 12월 24일
"Is there a reason why the transpose is written as .' instead of just '?"
Because .' is transpose (even if beginners often use the complex conjugate transpose instead):
Using the correct operator has several benefits:
  • it makes the intent clear
  • it makes your code more generalized (assuming the rest of your algorithm can also handle complex numbers)
  • it increases trust in your code
  • it is the correct operator

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2023년 12월 21일

편집:

2023년 12월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by