# How to replace ones and zeros in a logical vector with vectors of corresponding length?

조회 수: 1(최근 30일)
Edward Schreiner 2021년 8월 10일
댓글: Edward Schreiner 2021년 8월 10일
I need to recombine two vectors which where seperatet by logical indexing:
idx = [1 0 0 1 1 0 0]; % appearance of logical index
a = [2 3 4]; % the values of a have to replace the ones in indx in the same order
b = [9 8 7 7]; % the values of b have to replace the zeros in indx in the same order
The solution should look like this:
c = [2 9 8 3 4 7 7]; % recombined vector

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

### 채택된 답변

Scott MacKenzie 2021년 8월 10일
idx = [1 0 0 1 1 0 0]; % appearance of logical index
a = [2 3 4]; % the values of a have to replace the ones in indx in the same order
b = [9 8 7 7];
c = [a b];
idx = logical(idx);
c = [c(idx) c(~idx)]
c = 1×7
2 9 8 3 4 7 7
##### 댓글 수: 1표시숨기기 없음
Edward Schreiner 2021년 8월 10일
Thank you too! I'll accept this as i find it even more elegant.

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

### 추가 답변(1개)

Yongjian Feng 2021년 8월 10일
Try this:
idx = [1 0 0 1 1 0 0]; % appearance of logical index
a = [2 3 4]; % the values of a have to replace the ones in indx in the same order
b = [9 8 7 7]; % the values of b have to replace the zeros in indx in the same order
c = [];
aIdx = 1;
bIdx = 1;
for i=1:length(idx)
if idx(i) == 1
c(end+1)=a(aIdx);
aIdx = aIdx + 1;
else
c(end+1) = b(bIdx);
bIdx = bIdx + 1;
end
end
c
##### 댓글 수: 1표시숨기기 없음
Edward Schreiner 2021년 8월 10일
Thank you a lot! It works as intended.

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

### Community Treasure Hunt

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

Start Hunting!