필터 지우기
필터 지우기

How can a logical vector be converted to a numeric vector in which the values represent the number of zeros between ones?

조회 수: 3 (최근 30일)
I am searching for a simple way to convert a logical vector, to a vector in which the values represent the total number scalars between ones, and including the first 1 in the list. Essentially converting x to y where:
x = [1;1;1;0;0;1;0;1];
y = [1;1;3;3;3;2;2;1];
Any suggestions? Thanks!
RTT

채택된 답변

Ahmet Cecen
Ahmet Cecen 2016년 11월 10일
편집: Ahmet Cecen 2016년 11월 10일
Something along the lines of:
x = [1;1;1;0;0;1;0;1];
inds = find(x);
diffs = [inds(2:end);0]-inds;
diffs(end) = 1;
y = repelem(diffs, diffs); % By Guillaume
  댓글 수: 2
Guillaume
Guillaume 2016년 11월 10일
편집: Guillaume 2016년 11월 10일
I don't understand the logic of the algorithm.Why is the first element of diffs is removed and why is the last element set to 1? However, I can say that the loop is not needed and can be replaced by:
y = repelem(diffs, diffs);
Ahmet Cecen
Ahmet Cecen 2016년 11월 10일
Wow! What a nice function that I had never heard of. Super useful.
The example in the question is basically using the 1's in the matrix as nodes, and the 0's between 1's as the edge weights.
The algorithm is first finding where the ones are, then finds the distance between them ([inds(2:end);0] is aligning the next index with current for the subtraction.). It is a similar effect to circshift, but I didn't want to confuse the reader with periodicity when it is not used here. Last element is set to 1 simply assuming the list ends with a 1, as it is unclear from the question how a list ending with a 0 would be treated.

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

추가 답변 (1개)

Robert
Robert 2016년 12월 7일
Very elegant solution, thank you!
Cheers

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by