I have a dummy vector with 5000 rows and 1 column . I have some single 1 in this vector. No I want to change all 0 before the 1 to 1 and also change the 3 following 0 after the 1 to 1. But I don't know how. Could someone help me?Thank you a lot.

조회 수: 1 (최근 30일)
In gener i would like to change
0 0 1 0 0 0 0
to
0 1 1 1 1 1 0

채택된 답변

Guillaume
Guillaume 2016년 10월 5일
One possibility, assuming you're using R2016b:
v = [0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0]; %for example
startseq = strfind(v, [0 1 0 0 0]); %strfind also work for finding sequences of numbers
v(startseq + (0:4)') = repmat([1 1 1 1 1], 1, numel(startseq));
If prior to R2016b, replace startseq + (0:4)' in the last line by:
bsxfun(@plus, startseq, (0:4)')
  댓글 수: 3
Guillaume
Guillaume 2016년 10월 5일
What is wrong is that you're using a version before R2016b.
As I wrote in my answer, If prior to R2016b, replace .... Follow the instructions!
FC93
FC93 2016년 10월 5일
Now I got what I wanted. Thank you very much fo your help. I just replaced startseq + (0:4)' with bsxfun(@plus, startseq, (0:4)'), but I am using MATLAB R2016a, so maybe thats why.
Have a nice day.

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

추가 답변 (2개)

KSSV
KSSV 2016년 10월 5일
A = [0 0 1 0 0 0 0] ;
B = A ;
B(A==1) = 0 ; % replace 1 with 0
B(A==0) = 1 ; % replace 0 with 1
  댓글 수: 3
FC93
FC93 2016년 10월 5일
thank you for your answer but I have a vector with the dimensions 5000x1 and approximately 170 ones. I just need to change the 0 before the 1 to 1 and the following three 0 after the 1 to 1. Do you know how I could do it?
An example [0;0;0;0;0;0;0; 1;0;0;0;0;0;0;0;0;] to [0;0;0;0;0;0; 1; 1; 1; 1; 1;0;0;0;0;0;]
The problem is that I need a function because I have over 5000 values. Thank you

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


Jos (10584)
Jos (10584) 2016년 10월 5일
편집: Jos (10584) 2016년 10월 5일
You can convolve your vector with a series of ones using filter, which will add a specific number of ones after each array
a = [0 0 1 0 0 0 0 0]
filter(ones(1,4),1,a) % add 3 ones
% [0 0 1 1 1 1 0 0]
Using something similar on the reversed array will give you what you want.
FUN = @(V,AddN) filter(ones(1,AddN+1),1,V) % a function for convenience
V = [0 0 1 0 0 0 0 0 0 1 1 0 0]
FUN(V,3) | fliplr(FUN(fliplr(V),1)) % add 3 ones after and 1 one before each 1 in V

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by